douludi8413 2016-02-12 12:42
浏览 74
已采纳

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

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条回答 默认 最新

  • dongqiangse6623 2016-02-12 13:23
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频