Last active
October 3, 2024 20:45
-
-
Save dlisboa/aae33fd3ed049a7607cf75d821d47a68 to your computer and use it in GitHub Desktop.
Safer enums
This file contains hidden or 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 | |
| // inspiration: https://threedots.tech/post/safer-enums-in-go/ | |
| import "fmt" | |
| // don't use `type Role string` as it can accept any string | |
| type Role struct { | |
| s string | |
| } | |
| // define the enum's "consts" (but not really consts) | |
| // the idea is to put this in a package like roles.Admin so you can things | |
| // like: | |
| // | |
| // if user.Role == roles.Admin { | |
| // ... | |
| // } | |
| var Member = Role{"member"} | |
| var Admin = Role{"admin"} | |
| func main() { | |
| var r Role | |
| r = Member | |
| fmt.Println(r) | |
| r = Admin | |
| fmt.Println(r) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment