简体   繁体   中英

How to convert [ ][2]string to map[string] string in go?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM