我想在 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"
}
uj5u.com熱心網友回復:
是的,可以使用列舉索引宣告一個陣列陣列。
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
uj5u.com熱心網友回復:
從宣告中洗掉 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"
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512034.html
標籤:数组去枚举片
