英文:
How to get a package const value by name using reflect?
问题
这是一个包含一些常量的包。
package object
type Languaege int
const (
Javascript Languaege = iota
C
Cpp
Shell
)
//========================================
如果我知道类型 Language 的名称,我如何获取其值?
package main
func GetConstByName(name String) {
....
}
lang := GetConstByName("Shell")
英文:
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")
答案1
得分: 5
我不认为除了手动之外,你能做到这一点,如果你想让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
英文:
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\n", C, C, NewLanguage("C"))
fmt.Printf("Shell is %d: %s: %d\n", Shell, Shell, NewLanguage("Shell"))
}
This outputs
C is 1: C: 1
Shell is 3: Shell: 3
答案2
得分: -4
你正在尝试滥用反射。在这种情况下,幸运的是,它不会起作用。如果你想要将字符串键映射到一些关联的值,那么请使用map[string]someValueType
。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论