dsw1608 2016-07-13 11:14
浏览 628
已采纳

如何在go中将[] [2] string转换为map [string]字符串?

I am retrieving an object called DockerInfo which has a field inside it called SystemStatus which is [][2]string, then in order to access the elements inside SystemStatus I am doing this, for example if the 4th element in SystemStatus is ["Nodes","6"] then to access the number 6

dockerinfo.SystemStatus[3][1]

But the Nodes elements are not fixed in 4th position always so I can not use indexing and instead I want to find number of nodes by for example writing

dockerinfo.SystemStatus["Nodes"] 

How can I do that? Or how to transform the SystemStatus to map[string]string format?

  • 写回答

1条回答 默认 最新

  • douzhankui0758 2016-07-13 11:38
    关注

    Use a simple for loop to iterate over the values of the dockerinfo.SystemStatus slice, and compare the first value to "Nodes":

    for _, v := range dockerinfo.SystemStatus {
        if v[0] == "Nodes" {
            // Got it!
            value := v[1] // This will be "6" in your example
            fmt.Println("Nodes value:", value)
            break
        }
    }
    

    This value will be of type string but it looks it holds a numerical data. If you want it as an int for example, you may use strconv.Atoi() to parse the number:

    value := v[1]
    if n, err := strconv.Atoi(value); err == nil {
        // n is of type int, use it like so
    } else {
        // Not a number!
    }
    

    If you have to lookup values many times, it may be profitable to build a map from it. This is how you could do it:

    ssmap := map[string]string{}
    for _, v := range dockerinfo.SystemStatus {
        ssmap[v[0]] = v[1]
    }
    
    // And then you can do simple lookup:
    if nodes, ok := ssmap["Nodes"]; ok {
        fmt.Println("Nodes value:", nodes)
    } else {
        // Nodes not found!
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用