Go,striket 的二维数组(或切片)

问题描述 投票:0回答:1

以下代码运行良好:

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

我认为使用切片一定可以,但我没有找到如何做到这一点!

arrays go struct slice
1个回答
0
投票

我找到了如何使用切片而不是数组:

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] 设置为全局,在主函数之外定义它,有人知道该怎么做吗?

© www.soinside.com 2019 - 2024. All rights reserved.