以下代码运行良好:
package main
import (
"fmt"
)
type Node struct {
north int
east int
south int
west int
}
func main() {
roomsX := 5
roomsY := 5
test := [5][5]Node{}
for x := 0; x < roomsX; x++ {
for y := 0; y < roomsY; y++ {
test[x][y] = Node{}
}
}
fmt.Println(test)
fmt.Println(test[0][0].north)
fmt.Println(test[4][4].north)
}
...但如果我使用变量而不是数字,则不会:
test := [roomsX][roomsY]Node{}
出现以下错误:
test2.go:17:11:数组长度 roomsX 无效, test2.go:17:19:无效的数组长度 roomsY
我认为使用切片一定可以,但我没有找到如何做到这一点!
我找到了如何使用切片而不是数组:
package main
import (
"fmt"
)
type Node struct {
north int
east int
south int
west int
}
func main() {
roomsX := 6
roomsY := 5
test := make([][]Node, roomsX)
for i := range test {
test[i] = make([]Node, roomsY)
}
for x := 0; x < roomsX; x++ {
for y := 0; y < roomsY; y++ {
test[x][y] = Node{}
}
}
fmt.Println(test)
fmt.Println(test[0][0].north)
fmt.Println(test[4][4].north)
}
...但现在我想将 [test] 设置为全局,在主函数之外定义它,有人知道该怎么做吗?