登录
首页 >  Golang >  Go问答

在 GO 中使用结构体定义枚举

来源:stackoverflow

时间:2024-03-20 18:54:31 262浏览 收藏

在 Go 语言中,由于缺乏枚举类型,需要采用替代方法来实现类似功能。可以使用结构体定义一个具有通用名称和距离太阳距离的“行星”结构体。然而,直接在结构体中定义常量会引发错误,提示“const initializer planet literal is not a constant”。

问题内容

我想枚举我的 go 程序中的行星。 每个行星都包含一个通用名称(例如:“金星”)和以天文单位表示的距太阳的距离(例如:0.722)

所以我写了这段代码:

type planet struct {
    commonname string
    distancefromthesuninau float64
}

const(
    venus planet = planet{"venus", 0.387}      // this is line 11
    mercury planet = planet{"mercury", 0.722}
    earth planet = planet{"eath", 1.0}
    mars planet = planet{"mars", 1.52}
    ...
)

但是 go 不让我编译这个,并给了我这个错误:

# command-line-arguments
./Planets.go:11: const initializer planet literal is not a constant
./Planets.go:12: const initializer planet literal is not a constant
./Planets.go:13: const initializer planet literal is not a constant
./Planets.go:14: const initializer planet literal is not a constant

你知道我该怎么做吗? 谢谢


解决方案


go 不支持枚举。您应该将枚举字段定义为 vars 或为了确保不变性,也许使用返回常量结果的函数。
例如:

type myStruct { ID int }

func EnumValue1() myStruct { 
    return myStruct { 1 } 
}

func EnumValue2() myStruct { 
    return myStruct { 2 } 
}

今天关于《在 GO 中使用结构体定义枚举》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

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