Skip to content

Instantly share code, notes, and snippets.

@m3g4p0p
Created October 15, 2021 19:35
Show Gist options
  • Save m3g4p0p/d55f51d8ef0d6229c0c8bb12d94f88d4 to your computer and use it in GitHub Desktop.
Save m3g4p0p/d55f51d8ef0d6229c0c8bb12d94f88d4 to your computer and use it in GitHub Desktop.
Another Safe Enum in Go
package main
import (
"errors"
"fmt"
)
type role string
const (
Unknown role = ""
Member role = "Member"
Moderator role = "Moderator"
Admin role = "Admin"
)
func CreateUser(r interface{}) error {
if _, ok := r.(role); !ok {
return errors.New(fmt.Sprintf("Invalid user %#v", r))
}
fmt.Println("Creating user with role", r)
return nil
}
func main() {
err := CreateUser("foo")
if err != nil {
fmt.Println(err)
}
err = CreateUser(Admin)
if err != nil {
fmt.Println(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment