It's a package having some constants.
package object
type Languaege int
const (
Javascript Languaege = iota
C
Cpp
Shell
)
//========================================
how can i get the value of a type Language if I know its name?
package main
func GetConstByName(name String) {
....
}
lang := GetConstByName("Shell")
I don't think you can do it except by hand if you want Language
to remain a const
integer type.
Here is what I would do - make Language implement Stringer which means you can print it too. You can then invert languageMap
to turn language strings into 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
", C, C, NewLanguage("C"))
fmt.Printf("Shell is %d: %s: %d
", Shell, Shell, NewLanguage("Shell"))
}
This outputs
C is 1: C: 1
Shell is 3: Shell: 3
You're trying to abuse reflection. In this case, fortunately for you, it will not work. If you want to map string keys to some associated values then use a map[string]someValueType
instead.