普通网友 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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀