go - GO 中的结构体枚举

标签 go enums

我想枚举我的 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/

相关文章:

php - 在PHP中解密由openssl_encrypt加密的AES-256-CBC密文时出现坏 block 大小错误

windows - 如何使用依赖于 libiconv 的 MinGW 安装 go 包

c# - 值为 0x0001 的枚举?

c# - 可以将泛型类型限制为枚举吗?

java - 无法使用带有方法的枚举的动态类参数实例化 EnumMap

c - golang 将内存转换为结构

go - 如何将日志写入文件

unit-testing - 当我删除 fmt.Println() 时,golang 中的猴子修补失败

java - 我应该测试枚举吗?

c# - 在C#中的ViewModel中公开模型中的枚举