如何在 Golang 中创建一个三维数组

我正在尝试创建一个包含块(如魔方)的三维数组。


我尝试了很多东西,但我无法让它工作。


func generateTiles(x int, y int, z int) [][][]*tile{

  var tiles [][][]*tile


  // Something here

  // resulting in a x by y by z array

  // filled with *tile


  return tiles

}

有什么建议?


holdtom
浏览 459回答 2
2回答

小唯快跑啊

您必须自行初始化每个图层。示例(在玩):tiles = make([][][]*tile, x)for i := range tiles {    tiles[i] = make([][]*tile, y)    for j := range tiles[i] {        tiles[i][j] = make([]*tile, z)    }}

婷婷同学_

出于性能原因,我个人会使用一维切片,我将其添加为替代方案:type Tile struct {&nbsp; &nbsp; x, y, z int}type Tiles struct {&nbsp; &nbsp; t&nbsp; &nbsp; &nbsp; &nbsp;[]*Tile&nbsp; &nbsp; w, h, d int}func New(w, h, d int) *Tiles {&nbsp; &nbsp; return &Tiles{&nbsp; &nbsp; &nbsp; &nbsp; t: make([]*Tile, w*h*d),&nbsp; &nbsp; &nbsp; &nbsp; w: w,&nbsp; &nbsp; &nbsp; &nbsp; h: h,&nbsp; &nbsp; &nbsp; &nbsp; d: d,&nbsp; &nbsp; }}// indexing based on http://stackoverflow.com/a/20266350/145587func (t *Tiles) At(x, y, z int) *Tile {&nbsp; &nbsp; idx := t.h*t.w*z + t.w*y&nbsp; &nbsp; return t.t[idx+x]}func (t *Tiles) Set(x, y, z int, val *Tile) {&nbsp; &nbsp; idx := t.h*t.w*z + t.w*y&nbsp; &nbsp; t.t[idx+x] = val}func fillTiles(w int, h int, d int) *Tiles {&nbsp; &nbsp; tiles := New(w, h, d)&nbsp; &nbsp; for x := 0; x < w; x++ {&nbsp; &nbsp; &nbsp; &nbsp; for y := 0; y < h; y++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for z := 0; z < d; z++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tiles.Set(x, y, z, &Tile{x, y, z})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return tiles}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go