我想枚举我的 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}
...
)
Run Code Online (Sandbox Code Playgroud)
但是 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
Run Code Online (Sandbox Code Playgroud)
你知道我该怎么做吗?谢谢
Go 不支持枚举。您应该将枚举字段定义为vars 或为了确保不变性,也许使用返回常量结果的函数。
例如:
type myStruct { ID int }
func EnumValue1() myStruct {
return myStruct { 1 }
}
func EnumValue2() myStruct {
return myStruct { 2 }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13037 次 |
| 最近记录: |