英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论