英文:
Convert array of strings to field name
问题
新手问题:
我想打印一个库的各种变量(这个名称正确吗?reflect.TypeOf(servers)
返回[]lib.Server
)
我想做类似这样的事情,但显然这样是行不通的:
servers, err := GetClient().GetServers() //调用外部API
serverVariables := []string{}
serverVariables = append(serverVariables, "Name")
serverVariables = append(serverVariables, "IPAddress")
for _, server := range servers {
for _, element := range serverVariables {
fmt.Println(server.element)
}
}
我已经能够做到以下这一点(但我想使用上面的方法):
servers, err := GetClient().GetServers() //调用外部API
for _, server := range servers {
fmt.Println(server.Name)
fmt.Println(server.IPAddress)
}
输出如下:
ServerNameOne
192.168.0.1
ServerNameTwo
192.168.0.2
英文:
Newbie question:
I want to print various variables of a library (is that the correct name? reflect.TypeOf(servers)
gives []lib.Server
)
I want to do something like this, but this obviously does not work:
servers, err := GetClient().GetServers() //call to external API
serverVariables := []string{}
serverVariables = append(serverVariables, "Name")
serverVariables = append(serverVariables, "IPAddress")
for _, server := range servers {
for _,element := range serverVariables {
fmt.Println(server.element)
}
}
What I already can do is the following (but I want to do it using the above approach):
servers, err := GetClient().GetServers() //call to external API
for _, server := range servers {
fmt.Println(server.Name)
fmt.Println(server.IPAddress)
}
giving the following output:
ServerNameOne
192.168.0.1
ServerNameTwo
192.168.0.2
答案1
得分: 0
反射是你可能想要使用的:
for _, server := range servers {
v := reflect.ValueOf(server)
for _, element := range serverVariables {
fmt.Println(v.FieldByName(element))
}
}
你还应该将 serverVariables
的初始化更改为 serverVariables := []string{}
Playground 示例:https://play.golang.org/p/s_kzIJ7-B7
我觉得你可能有一些使用 Python 或 JavaScript 等动态语言的经验。Go 是编译型且强类型的语言。除了反射较慢之外,在使用反射时编译器无法帮助你找到代码中的基本错误,最重要的是你会失去访问变量的类型信息。
更多信息请参考:http://blog.golang.org/laws-of-reflection
所以我强烈建议你保持当前的方法:
for _, server := range servers {
fmt.Println(server.Name)
fmt.Println(server.IPAddress)
}
英文:
Reflection is what you probably want to use:
for _, server := range servers {
v := reflect.ValueOf(server)
for _, element := range serverVariables {
fmt.Println(v.FieldByName(element))
}
}
You should also change serverVariables
initialization to be serverVariables := []string{}
Playground example: https://play.golang.org/p/s_kzIJ7-B7
It seems to me that you have experience in some dynamic language like Python or JavaScript. Go is compiled and strongly typed. Besides reflection being slower, when using it compiler can't help you with finding basic errors in your code and what is most important you lose type of the accessed variable.
More info on http://blog.golang.org/laws-of-reflection
So I strongly recommend you to keep your current approach:
for _, server := range servers {
fmt.Println(server.Name)
fmt.Println(server.IPAddress)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论