我想枚举我的 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 不支持枚举。您应该将枚举字段定义为 var
或为了确保不变性,可能使用返回常量结果的函数。
例如:
type myStruct { ID int }
func EnumValue1() myStruct {
return myStruct { 1 }
}
func EnumValue2() myStruct {
return myStruct { 2 }
}
关于go - GO 中的结构体枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470766/