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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这显示了使得更容易制作n维切片的图案.
您确定需要多维切片吗?如果在编译时已知/可导出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)
}
Run Code Online (Sandbox Code Playgroud)
(还在这里)
产量
[[[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]]]
Run Code Online (Sandbox Code Playgroud)