我正在尝试创建一个包含块的三维数组(如rubiks-cube).
我尝试了很多东西,但我无法让它发挥作用.
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
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?
nem*_*emo 10
您必须自己初始化每个图层.示例(正在播放):
tiles = make([][][]*tile, x)
for i := range tiles {
tiles[i] = make([][]*tile, y)
for j := range tiles[i] {
tiles[i][j] = make([]*tile, z)
}
}
Run Code Online (Sandbox Code Playgroud)
出于性能原因,我个人会使用一维切片,我将其添加为替代方案:
type Tile struct {
x, y, z int
}
type Tiles struct {
t []*Tile
w, h, d int
}
func New(w, h, d int) *Tiles {
return &Tiles{
t: make([]*Tile, w*h*d),
w: w,
h: h,
d: d,
}
}
// indexing based on http://stackoverflow.com/a/20266350/145587
func (t *Tiles) At(x, y, z int) *Tile {
idx := t.h*t.w*z + t.w*y
return t.t[idx+x]
}
func (t *Tiles) Set(x, y, z int, val *Tile) {
idx := t.h*t.w*z + t.w*y
t.t[idx+x] = val
}
func fillTiles(w int, h int, d int) *Tiles {
tiles := New(w, h, d)
for x := 0; x < w; x++ {
for y := 0; y < h; y++ {
for z := 0; z < d; z++ {
tiles.Set(x, y, z, &Tile{x, y, z})
}
}
}
return tiles
}
Run Code Online (Sandbox Code Playgroud)