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

huangapple go评论92阅读模式
英文:

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

问题

我想在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)
  
    // 编译错误:"Yummy Apple"(类型为string)无法表示为MyType类型
	produce[Red][Apple] = "Yummy Apple"
}

我会帮你翻译这段代码,不会回答关于翻译的问题。

英文:

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

答案1

得分: 1

将声明中的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"
}
英文:

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

答案2

得分: 1

是的,可以使用枚举索引声明一个数组的数组。

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

英文:

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

    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

huangapple
  • 本文由 发表于 2022年10月6日 12:12:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/73968600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定