Get an arbitrary key/item from a map

前端 未结 6 1469
攒了一身酷
攒了一身酷 2021-02-01 12:59

I am new to Go and now I want to get an arbitrary item from a map; what\'s the idiomatic way to do that? I can only think of something like this:

func get_some_k         


        
6条回答
  •  时光说笑
    2021-02-01 13:12

    In my case, the map only had one key which I needed to extract so for that you can do:

        var key string
        var val string
        for k, v := range myMap {
            key = k
            val = v
            break
        }
    

    For multiple keys you could do something like,

    func split_map(myMap map[string]string, idx int) (string[], string[]) {
        keys := make([]string, len(myMap))
        values := make([]string, len(myMap))
        count := 0
        for k, v := range myMap {
            keys[count] = k
            values[count] = v
            count = count + 1
        }
        return keys, values
    }
    

    While for accessing ith element,

    func get_ith(myMap map[string]string, idx int) (string, string) {
        count := 0
        for k, v := range myMap {
            if idx == count {
                return k, v
            }
            count = count + 1
        }
        return "", ""
    }
    

提交回复
热议问题