在golang中,从地图获取一部分值有很好的方法吗? [英] In golang is there a nice way of getting a slice of values from a map?

查看:146
本文介绍了在golang中,从地图获取一部分值有很好的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一张地图,有没有更好的方法来得到一个值v然后

  package main 
导入(
fmt


func main(){
m:= make(map [int] string)

m [1] =a
m [2] =b
m [3] =c
m [4] =d

//这可以做得更好吗?
v:= make([] string,len(m),len(m))
idx:= 0
for _,value:= range m {
v [idx] =价值
idx ++
}

fmt.Println(v)
}

是否有地图的内置功能?在Go包中有一个函数,或者这是最好的代码吗?

。没有内建的方法来做到这一点。



作为一个方面说明,您可以在创建切片时省略容量参数:

  v:= make([] string,len(m))

容量暗示与此处的长度相同。


If I have a map m is there a better way of getting a slice of the values v then

package main
import (
  "fmt"
)

func main() {
    m := make(map[int]string)

    m[1] = "a"
    m[2] = "b"
    m[3] = "c"
    m[4] = "d"

    // Can this be done better?
    v := make([]string, len(m), len(m))
    idx := 0
    for  _, value := range m {
       v[idx] = value
       idx++
    }

    fmt.Println(v)
 }

Is there a built feature of a map? Is there a function in a Go package, or is this the best code to do if I have to?

解决方案

Unfortunately, no. There is no builtin way to do this.

As a side note, you can omit the capacity argument in your slice creation:

v := make([]string, len(m))

The capacity is implied to be the same as the length here.

这篇关于在golang中,从地图获取一部分值有很好的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆