登录
首页 >  Golang >  Go问答

能否使用枚举索引来定义多维数组?

来源:stackoverflow

时间:2024-02-26 22:18:22 459浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《能否使用枚举索引来定义多维数组?》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

我想在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"
}

正确答案


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

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

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>