bug^君
2014-01-26 11:48
采纳率: 25%
浏览 229

戈朗-从地图上获得一个键的切片

Is there any simpler/nicer way of getting a slice of keys from a map in Go?

Currently I am iterating over the map and copying the keys to a slice:

i := 0
keys := make([]int, len(mymap))
for k := range mymap {
    keys[i] = k
    i++
}

转载于:https://stackoverflow.com/questions/21362950/golang-getting-a-slice-of-keys-from-a-map

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • ~Onlooker 2014-01-26 12:53
    已采纳

    For example,

    package main
    
    func main() {
        mymap := make(map[int]string)
        keys := make([]int, 0, len(mymap))
        for k := range mymap {
            keys = append(keys, k)
        }
    }
    

    To be efficient in Go, it's important to minimize memory allocations.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • 妄徒之命 2014-01-26 11:52

    A nicer way to do this would be to use append:

    keys = []int{}
    for k := range mymap {
        keys = append(keys, k)
    }
    

    Other than that, you’re out of luck—Go isn’t a very expressive language.

    评论
    解决 无用
    打赏 举报
  • derek5. 2015-01-08 19:36

    This is an old question, but here's my two cents. PeterSO's answer is slightly more concise, but slightly less efficient. You already know how big it's going to be so you don't even need to use append:

    keys := make([]int, len(mymap))
    
    i := 0
    for k := range mymap {
        keys[i] = k
        i++
    }
    

    In most situations it probably won't make much of a difference, but it's not much more work, and in my tests (using a map with 1,000,000 random int64 keys and then generating the array of keys ten times with each method), it was about 20% faster to assign members of the array directly than to use append.

    Although setting the capacity eliminates reallocations, append still has to do extra work to check if you've reached capacity on each append.

    评论
    解决 无用
    打赏 举报
  • 撒拉嘿哟木头 2016-04-03 15:55

    You also can take an array of keys with type []Value by method MapKeys of struct Value from package "reflect":

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func main() {
        abc := map[string]int{
            "a": 1,
            "b": 2,
            "c": 3,
        }
    
        keys := reflect.ValueOf(abc).MapKeys()
    
        fmt.Println(keys) // [a b c]
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题