3 回答
TA贡献1848条经验 获得超2个赞
如果您尝试获取字符串“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"
TA贡献1963条经验 获得超6个赞
根据godoc。这个工作有一个生成器,叫做stringer,在golang.org/x/tools/cmd/stringer
使用stringer,您可以这样做。
/*enum.go*/
//go:generate stringer -type=Pill
type Pill int
const (
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 of
func (Pill) String() string
That method will translate the value of a Pill constant to the string
representation of the respective constant name, so that the call
fmt.Print(painkiller.Aspirin)
will print the string "Aspirin".
TA贡献1860条经验 获得超9个赞
将选定的 id 转换为Gender类型。例子:
selectedID := 5
selectedGender := Gender(selectedID)
fmt.Println(selectedGender == Female) // true
anotherSelectedID := 5
selectedMemberType := MemberType(anotherSelectedID)
fmt.Println(selectedMemberType == VIP) // true
游乐场: https: //play.golang.org/p/pfmJ0kg7cO3
- 3 回答
- 0 关注
- 721 浏览
添加回答
举报