我想在我的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
您是否知道我该怎么办? 谢谢
答案 0 :(得分:0)
Go不支持枚举。您应该将枚举字段定义为var
或为了确保不变性,也许使用返回恒定结果的函数。
例如:
type myStruct { ID int }
func EnumValue1() myStruct {
return myStruct { 1 }
}
func EnumValue2() myStruct {
return myStruct { 2 }
}