Created
October 15, 2021 19:35
-
-
Save m3g4p0p/d55f51d8ef0d6229c0c8bb12d94f88d4 to your computer and use it in GitHub Desktop.
Another Safe Enum in Go
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
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