如何在golang中按值获取枚举变量名?

我用enum来定义id和text值的关系,但是我用id作为enum值,因为我不能用id作为变量名


type Gender uint8

type MemberType uint8


const (

    Male Gender = 2

    Female Gender = 5


    Standard MemberType = 2

    VIP MemberType = 5

)

现在我从 Gender 表和 MemberType 表中选择了 id 5,如何使用它来获取 Gender 的文本“Female”和 MemberType 的文本“VIP”?


墨色风雨
浏览 722回答 3
3回答

慕尼黑5688855

如果您尝试获取字符串“Female”和“VIP”var genders = map[uint8]string{    2: "Male",    5: "Female",}var memberTypes = map[uint8]string{    2: "Standard",    5: "VIP",}或者:var genders = map[Gender]string{    Male: "Male",    Female: "Female",}var memberTypes = map[MemberType]string{    Standard: "Standard",    VIP: "VIP",}然后你会有类似的东西 id := 5 fmt.Println(genders[id]) // "Female" fmt.Println(memberTypes[id]) // "VIP" // or... fmt.Println(genders[Gender(id)]) // "Female" fmt.Println(memberTypes[MemberType(id)]) // "VIP"

神不在的星期二

根据godoc。这个工作有一个生成器,叫做stringer,在golang.org/x/tools/cmd/stringer使用stringer,您可以这样做。/*enum.go*///go:generate stringer -type=Pilltype Pill intconst (    Placebo Pill = iota    Aspirin    Ibuprofen    Paracetamol    Acetaminophen = Paracetamol)保存enum.go,然后运行go generate。stringer 将为您完成所有工作。in the same directory will create the file pill_string.go, in package painkiller, containing a definition offunc (Pill) String() stringThat method will translate the value of a Pill constant to the stringrepresentation of the respective constant name, so that the callfmt.Print(painkiller.Aspirin)will print the string "Aspirin".

慕码人2483693

将选定的 id 转换为Gender类型。例子:selectedID := 5selectedGender := Gender(selectedID)fmt.Println(selectedGender == Female) // trueanotherSelectedID := 5selectedMemberType := MemberType(anotherSelectedID)fmt.Println(selectedMemberType == VIP) // true游乐场: https: //play.golang.org/p/pfmJ0kg7cO3
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go