Skip to content

Instantly share code, notes, and snippets.

@kendellfab
Created June 9, 2022 13:02
Show Gist options
  • Save kendellfab/bff8a3bc29bd7fe63d99a14256965ce7 to your computer and use it in GitHub Desktop.
Save kendellfab/bff8a3bc29bd7fe63d99a14256965ce7 to your computer and use it in GitHub Desktop.
Go Enums
type Role int
const (
RoleUnknown Role = iota
_
_
RoleUser
_
_
RoleAdmin
)
var roleStrings = []string{"Unknown", "", "", "User", "", "", "Admin"}
func (r Role) String() string {
return roleStrings[r]
}
func RoleFromString(r string) Role {
for idx, elem := range roleStrings {
if elem == r {
return Role(idx)
}
}
return RoleUnknown
}
func (r *Role) UnmarshalJSON(b []byte) error {
roleStr := strings.Trim(string(b), `"`)
*r = RoleFromString(roleStr)
return nil
}
func (r Role) MarshalJSON() ([]byte, error) {
return json.Marshal(r.String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment