Skip to content

Instantly share code, notes, and snippets.

@dlisboa
Last active October 3, 2024 20:45
Show Gist options
  • Select an option

  • Save dlisboa/aae33fd3ed049a7607cf75d821d47a68 to your computer and use it in GitHub Desktop.

Select an option

Save dlisboa/aae33fd3ed049a7607cf75d821d47a68 to your computer and use it in GitHub Desktop.
Safer enums
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