【问题标题】:Create 3-dimensional slice (or more than 3)创建 3 维切片(或超过 3 个)
【发布时间】:2012-11-29 05:47:54
【问题描述】:

如何在 Go 中创建 3(或更多)维切片?

【问题讨论】:

    标签: arrays go slice


    【解决方案1】:
    var xs, ys, zs = 5, 6, 7 // axis sizes
    var world = make([][][]int, xs) // x axis
    func main() {
        for x := 0; x < xs; x++ {
            world[x] = make([][]int, ys) // y axis
            for y := 0; y < ys; y++ {
                world[x][y] = make([]int, zs) // z axis
                for z := 0; z < zs; z++ {
                    world[x][y][z] = (x+1)*100 + (y+1)*10 + (z+1)*1
                }
            }
        }
    }
    

    这显示了更容易制作 n 维切片的模式。

    【讨论】:

    • 希望我们可以直接说 world:=make([11,100][11,100][11,100]int) where 11=len, 100=cap 并直接使用 world[x][y][z] 引用...
    【解决方案2】:

    您确定需要多维切片吗?如果 n 维空间的维度在编译时是已知的/可导出的,则使用数组更容易并且运行时访问性能更好。示例:

    package main
    
    import "fmt"
    
    func main() {
            var world [2][3][5]int
            for i := 0; i < 2*3*5; i++ {
                    x, y, z := i%2, i/2%3, i/6
                    world[x][y][z] = 100*x + 10*y + z
            }
            fmt.Println(world)
    }
    

    (也叫here


    输出

    [[[0 1 2 3 4] [10 11 12 13 14] [20 21 22 23 24]] [[100 101 102 103 104] [110 111 112 113 114] [120 121 122 123 124]]]
    

    【讨论】:

    • 这是一种处理循环的有趣方式。数学依据是什么?我无法完全解决。
    • 我的直觉是 i%2,i%3,i%5。
    • "Unsimplified" 它类似于:x = (i/(1))%2, y = (i/(1.2))%3, z = (i/(1.2.3)) %5。 HTH ;-)
    猜你喜欢
    • 2016-07-29
    • 2022-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 2021-10-30
    • 2014-12-23
    • 2017-11-15
    相关资源
    最近更新 更多