英文:
Create 3-dimensional slice (or more than 3)
问题
如何在Go中创建一个3(或更多)维度的切片?
英文:
How do you create a 3 (or more) dimensional slice in Go?
答案1
得分: 5
var xs, ys, zs = 5, 6, 7 // 轴的大小
var world = make([][][]int, xs) // x轴
func main() {
for x := 0; x < xs; x++ {
world[x] = make([][]int, ys) // y轴
for y := 0; y < ys; y++ {
world[x][y] = make([]int, zs) // z轴
for z := 0; z < zs; z++ {
world[x][y][z] = (x+1)*100 + (y+1)*10 + (z+1)*1
}
}
}
}
这显示了一个模式,使得创建n维切片更容易。
英文:
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
}
}
}
}
That shows the pattern which makes it easier to make n-dimensional slices.
答案2
得分: 5
你确定你需要一个多维切片吗?如果 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)
}
(也可以在这里查看)
输出
[[[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]]]
英文:
Are you sure you need a multi dimensional slice? If the dimensions of the n-dimensional space are known/derivable at compile time then using an array is easier and better run time access performing. Example:
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)
}
(Also here)
Output
[[[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]]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论