Iterating over all the keys of a map

前端 未结 4 2106
借酒劲吻你
借酒劲吻你 2020-12-12 11:33

Is there a way to get a list of all the keys in a Go language map? The number of elements is given by len(), but if I have a map like:

m := map         


        
相关标签:
4条回答
  • 2020-12-12 12:12

    https://play.golang.org/p/JGZ7mN0-U-

    for k, v := range m { 
        fmt.Printf("key[%s] value[%s]\n", k, v)
    }
    

    or

    for k := range m {
        fmt.Printf("key[%s] value[%s]\n", k, m[k])
    }
    

    Go language specs for for statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.

    0 讨论(0)
  • 2020-12-12 12:19

    Is there a way to get a list of all the keys in a Go language map?

    ks := reflect.ValueOf(m).MapKeys()
    

    how do I iterate over all the keys?

    Use the accepted answer:

    for k, _ := range m { ... }
    
    0 讨论(0)
  • 2020-12-12 12:26

    Here's some easy way to get slice of the map-keys.

    // Return keys of the given map
    func Keys(m map[string]interface{}) (keys []string) {
        for k := range m {
            keys = append(keys, k)
        }
        return keys
    }
    
    // use `Keys` func
    func main() {
        m := map[string]interface{}{
            "foo": 1,
            "bar": true,
            "baz": "baz",
        }
        fmt.Println(Keys(m)) // [foo bar baz]
    }
    
    0 讨论(0)
  • 2020-12-12 12:28

    This is also an option

     for key, element := range myMap{
        fmt.Println("Key:", key, "Element:", element)
     }
    
    0 讨论(0)
提交回复
热议问题