我使用enum来定义id和文本值之间的关系,但是我使用id作为枚举值,因为我不能使用id作为变量名
type Gender uint8
type MemberType uint8
const (
Male Gender = 2
Female Gender = 5
Standard MemberType = 2
VIP MemberType = 5
)
现在我已经从“性别”表和“会员类型”表中选择了ID 5,如何使用它来获取“性别”的文本“女性”和“会员类型”的文本“ VIP”?
答案 0 :(得分:1)
将所选ID设置为Gender
类型。示例:
selectedID := 5
selectedGender := Gender(selectedID)
fmt.Println(selectedGender == Female) // true
anotherSelectedID := 5
selectedMemberType := MemberType(anotherSelectedID)
fmt.Println(selectedMemberType == VIP) // true
答案 1 :(得分:1)
如果您尝试获取字符串“ 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"
答案 2 :(得分:0)
根据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
。纵梁将为您做好一切。
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".
答案 3 :(得分:0)
对于每种枚举类型,您都可以使用单独的方法来获取字符串 像这样的值:-
package main
import (
"fmt"
)
type Gender uint8
type MemberType uint8
const (
Male Gender = 2
Female Gender = 5
Standard MemberType = 2
VIP MemberType = 5
)
func (data Gender) String() string {
switch data {
case Male:
return "Male"
case Female:
return "Female"
default:
return "unknown"
}
}
func (data MemberType) String() string {
switch data {
case Standard:
return "Standard"
case VIP:
return "VIP"
default:
return "unknown"
}
}
func main() {
fmt.Println(Male.String())
fmt.Println(Female.String())
fmt.Println(VIP.String())
fmt.Println(Standard.String())
}