亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在golang中按值獲取枚舉變量名?

如何在golang中按值獲取枚舉變量名?

Go
墨色風雨 2022-04-26 14:32:26
我用enum來定義id和text值的關系,但是我用id作為enum值,因為我不能用id作為變量名type Gender uint8type MemberType uint8const (    Male Gender = 2    Female Gender = 5    Standard MemberType = 2    VIP MemberType = 5)現在我從 Gender 表和 MemberType 表中選擇了 id 5,如何使用它來獲取 Gender 的文本“Female”和 MemberType 的文本“VIP”?
查看完整描述

3 回答

?
慕尼黑5688855

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"


查看完整回答
反對 回復 2022-04-26
?
神不在的星期二

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".


查看完整回答
反對 回復 2022-04-26
?
慕碼人2483693

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


查看完整回答
反對 回復 2022-04-26
  • 3 回答
  • 0 關注
  • 794 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號