我不認爲你可以這樣做,除非你想要Language
保持const
整數類型。
這是我會做 - 讓語言工具Stringer這意味着你可以打印它。然後,您可以反轉languageMap
把語言字符串爲Language
Playground link
package main
import "fmt"
type Language int
const (
Javascript Language = iota
C
Cpp
Shell
)
var languageMap = map[Language]string{
Javascript: "Javascript",
C: "C",
Cpp: "Cpp",
Shell: "Shell",
}
func (l Language) String() string {
return languageMap[l]
}
var languageMapReverse map[string]Language
func NewLanguage(languageName string) Language {
if languageMapReverse == nil {
languageMapReverse = make(map[string]Language)
for l, name := range languageMap {
languageMapReverse[name] = l
}
}
return languageMapReverse[languageName]
}
func main() {
fmt.Printf("C is %d: %s: %d\n", C, C, NewLanguage("C"))
fmt.Printf("Shell is %d: %s: %d\n", Shell, Shell, NewLanguage("Shell"))
}
此輸出
C is 1: C: 1
Shell is 3: Shell: 3