Home > database >  Is it possible to declare a multidimensional array using enumerated indexes?
Is it possible to declare a multidimensional array using enumerated indexes?

Time:10-06

I want to define a two dimension array or slice in Go and use enumerated values to access the data in the array. The following will not compile and I am hoping that you can help me to figure out how to make it work.

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"
}

CodePudding user response:

Yes, it is possible to declare an array of arrays using enumerated indexes.

const (
    Red  Color = 1
    Blue Color = 2
    MaxColor = Blue

    Apple     Fruit = 1
    BlueBerry Fruit = 2
    MaxFruit = BlueBerry
)

type (
    Color int
    Fruit int
)

const (
    Red      Color = 1
    Blue     Color = 2
    NumColor       = 3

    Apple     Fruit = 1
    BlueBerry Fruit = 2
    NumFruit        = 3
)

var produce [NumColor][NumFruit]string
produce[Red][Apple] = "Yummy Apple"
 

https://go.dev/play/p/AxwcxLE3iJX

CodePudding user response:

Remove MyType from declaration. Then it will work.

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"
}
  • Related