Created
November 26, 2023 16:09
-
-
Save dimitrilw/89311f35c0416944529230594e0959b2 to your computer and use it in GitHub Desktop.
Go (golang) enum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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