Created
June 9, 2022 13:02
-
-
Save kendellfab/bff8a3bc29bd7fe63d99a14256965ce7 to your computer and use it in GitHub Desktop.
Go Enums
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
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