将字符串数组转换为字段名称

将字符串数组转换为字段名称

问题描述:

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

新手问题: 我要打印库的各种变量(这是正确的名称吗? reflect .TypeOf(servers) code>给出了 [] lib.Server code>) p>

我想做这样的事情,但这显然行不通:

 服务器,错误:= GetClient()。GetServers()//调用外部API 
 
serverVariables:= [] string {} 
serverVariables = append(serverVariables,“ 名称“)
serverVariables = append(serverVariables,” IPAddress“)
 
对于_,服务器:=范围服务器{
 _,元素:=范围serverVariables {
 fmt.Println(server.element)
}  
} 
  code>  pre> 
 
 

我已经可以做的事情如下(但我想使用上述方法来做): p> servers,err:= GetClient()。GetServers()//调用外部API for _,server:=范围服务器{ fmt.Println(server.Name) fmt.Println (server.IPAddress) } code> pre>

给出以下输出: p>

  Serv  erNameOne 
192.168.0.1 
ServerNameTwo 
192.168.0.2 
  code>  pre> 
  div>

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)
}