我想列举一下我的围棋程序中的行星。每颗行星都有一个共同的名字(例如:“金星”)和天文单位距离太阳的距离(例如: 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你知道我能做什么吗?谢谢
发布于 2018-11-25 19:43:20
Go不支持枚举。您应该将枚举字段定义为var,或者为了确保不可变,可以使用返回常量结果的函数。
例如:
type myStruct { ID int }
func EnumValue1() myStruct {
return myStruct { 1 }
}
func EnumValue2() myStruct {
return myStruct { 2 }
}https://stackoverflow.com/questions/53470766
复制相似问题