普通网友 2016-10-01 09:11
浏览 35
已采纳

在Go中创建2D切片的简洁方法是什么?

I am learning Go by going through A Tour of Go. One of the exercises there asks me to create a 2D slice of dy rows and dx columns containing uint8. My current approach, which works, is this:

a:= make([][]uint8, dy)       // initialize a slice of dy slices
for i:=0;i<dy;i++ {
    a[i] = make([]uint8, dx)  // initialize a slice of dx unit8 in each of dy slices
}

I think that iterating through each slice to initialize it is too verbose. And if the slice had more dimensions, the code would become unwieldy. Is there a concise way to initialize 2D (or n-dimensional) slices in Go?

  • 写回答

3条回答 默认 最新

  • doumingo04696 2016-10-01 13:08
    关注

    There isn't a more concise way, what you did is the "right" way; because slices are always one-dimensional but may be composed to construct higher-dimensional objects. See this question for more details: Go: How is two dimensional array's memory representation.

    One thing you can simplify on it is to use the for range construct:

    a := make([][]uint8, dy)
    for i := range a {
        a[i] = make([]uint8, dx)
    }
    

    Also note that if you initialize your slice with a composite literal, you get this for "free", for example:

    a := [][]uint8{
        {0, 1, 2, 3},
        {4, 5, 6, 7},
    }
    fmt.Println(a) // Output is [[0 1 2 3] [4 5 6 7]]
    

    Yes, this has its limits as seemingly you have to enumerate all the elements; but there are some tricks, namely you don't have to enumerate all values, only the ones that are not the zero values of the element type of the slice. For more details about this, see Keyed items in golang array initialization.

    For example if you want a slice where the first 10 elements are zeros, and then follows 1 and 2, it can be created like this:

    b := []uint{10: 1, 2}
    fmt.Println(b) // Prints [0 0 0 0 0 0 0 0 0 0 1 2]
    

    Also note that if you'd use arrays instead of slices, it can be created very easily:

    c := [5][5]uint8{}
    fmt.Println(c)
    

    Output is:

    [[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]]
    

    In case of arrays you don't have to iterate over the "outer" array and initialize "inner" arrays, as arrays are not descriptors but values. See blog post Arrays, slices (and strings): The mechanics of 'append' for more details.

    Try the examples on the Go Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?