Java 的枚舉具有有用的方法“valueOf(string)”,它通過(guò)名稱返回 const 枚舉成員。前任。enum ROLE { FIRST("First role"), SECOND("Second role") private final String label; private ROLE(label String) { this.label = label; } public String getLabel() { return label; }}// in other place of code we can do:ROLE.valueOf("FIRST").getLabel(); // get's "First role"例如,在 html 表單的選擇提交到服務(wù)器之后,此行為很有用。我們有字符串表示需要轉(zhuǎn)換成真正的枚舉。有人可以告訴,golang 可以做同樣的行為嗎?歡迎使用代碼示例。
1 回答

慕容3067478
TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
不,Go 沒(méi)有枚舉。
所以你需要使用單獨(dú)的地圖:
const (
First = iota
Second
)
var byname = map[string]int {
"First": First,
"Second": Second,
}
如果您需要大量此類常量,請(qǐng)考慮使用代碼生成。
但實(shí)際上,我沒(méi)有看到您想要的功能的真正共鳴:常量幾乎是自描述的,因?yàn)樵谠创a中它們的名稱已經(jīng)是文本。 因此,“在運(yùn)行時(shí)獲取與文本字符串相關(guān)聯(lián)的數(shù)字”的唯一合理用例是解析一些數(shù)據(jù)/輸入,這就是使用查找圖的情況——一旦你像我一樣重新表述問(wèn)題,這很明顯.
- 1 回答
- 0 關(guān)注
- 138 瀏覽
添加回答
舉報(bào)
0/150
提交
取消