创建3维切片(或3个以上)

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


慕仙森
浏览 215回答 2
2回答

拉丁的传说

var xs, ys, zs = 5, 6, 7 // axis sizesvar world = make([][][]int, xs) // x axisfunc main() {&nbsp; &nbsp; for x := 0; x < xs; x++ {&nbsp; &nbsp; &nbsp; &nbsp; world[x] = make([][]int, ys) // y axis&nbsp; &nbsp; &nbsp; &nbsp; for y := 0; y < ys; y++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; world[x][y] = make([]int, zs) // z axis&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for z := 0; z < zs; z++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; world[x][y][z] = (x+1)*100 + (y+1)*10 + (z+1)*1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}这显示了使制作n维切片更容易的模式。

HUWWW

您确定需要多维切片吗?如果n维空间的维在编译时是已知的/可导出的,则使用数组会更容易且运行时访问效果更好。例子:package mainimport "fmt"func main() {&nbsp; &nbsp; &nbsp; &nbsp; var world [2][3][5]int&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < 2*3*5; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x, y, z := i%2, i/2%3, i/6&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; world[x][y][z] = 100*x + 10*y + z&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(world)}(也在这里)输出[[[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]]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go