是否可以使用枚举索引声明多维数组?

我想在 Go 中定义一个二维数组或切片,并使用枚举值来访问数组中的数据。以下将不会编译,我希望你能帮助我弄清楚如何让它工作。


type (

    Color  int

    Fruit  int

    MyType [][]string

)


const (

    Red  Color = 1

    Blue Color = 2


    Apple     Fruit = 1

    BlueBerry Fruit = 2

)


func DoIt() {

    produce := make([][]MyType, 0)

  

    // COMPILE ERROR: "Yummy Apple"' (type string) cannot be represented by the type MyType

    produce[Red][Apple] = "Yummy Apple"

}


收到一只叮咚
浏览 129回答 2
2回答

aluckdog

是的,可以使用枚举索引声明一个数组数组。    package main        import "fmt"        type (        Color int        Fruit int    )        const (        Red      Color = 1        Blue     Color = 2        NumColor       = 3            Apple     Fruit = 1        BlueBerry Fruit = 2        NumFruit        = 3    )        func main() {        var produce [NumFruit][NumColor]string        produce[Red][Apple] = "Yummy Apple"        fmt.Printf("%#v\n", produce)    }https://go.dev/play/p/AxwcxLE3iJX

红糖糍粑

从声明中删除 MyType。然后它会起作用。type (    Color int    Fruit int)const (    Red  Color = 1    Blue Color = 2    Apple     Fruit = 1    BlueBerry Fruit = 2)func DoIt() {    produce := make([][]string, 0)    produce[Red][Apple] = "Yummy Apple"}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go