Language
如果您想保持const
整数类型,我认为您只能手动完成。
这就是我要做的——让 Language 实现Stringer,这意味着你也可以打印它。然后您可以反转languageMap
以将语言字符串转换为Language
游乐场链接
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