普通网友 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条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计