Skip to content

Instantly share code, notes, and snippets.

@dimitrilw
Created November 26, 2023 16:09
Show Gist options
  • Save dimitrilw/89311f35c0416944529230594e0959b2 to your computer and use it in GitHub Desktop.
Save dimitrilw/89311f35c0416944529230594e0959b2 to your computer and use it in GitHub Desktop.
Go (golang) enum
package main
import "fmt" // for demo, below
type Weekday int
const (
Sunday Weekday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
// String is used by formatting functions; i.e., `fmt.Println(w)` automatically runs `fmt.Println(w.String)`
func (w Weekday) String() string {
return [7]string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}[w]
}
// EnumIndex returns the int value
func (w Weekday) EnumIndex() int {
return int(w)
}
func main() {
var x = Sunday
fmt.Println(x) // Output : Sunday
fmt.Println(x.String()) // Output : Sunday
fmt.Println(x.EnumIndex()) // Output : 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment