Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create 3-dimensional slice (or more than 3)

Tags:

arrays

slice

go

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

like image 307
kilves76 Avatar asked Feb 21 '26 02:02

kilves76


1 Answers

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.

like image 101
kilves76 Avatar answered Feb 23 '26 13:02

kilves76