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 關注
- 794 瀏覽
添加回答
舉報