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

How do you create a 3 (or more) dimensional slice in Go?

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.

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]]]