go语言实现枚举
type Season int
const (
Summer Season = iota + 1
Autumn
Winter
Spring
)
type ArticleState int
const (
Draft ArticleState = iota + 1
Published
Deleted
)
func checkArticleState(state ArticleState) bool {
// ...
}
func main() {
// 两个操作数类型不匹配,编译错误
fmt.Println(Autumn == Draft)
// 参数类型不匹配,但是因为 ArticleState 底层的类型是 int 所以传递 int 的时候会发生隐式类型转换,所以不会报错
checkArticleState(100)
}
参考:Go 里面该怎么实现枚举 · Issue #73 · kevinyan815/gocookbook · GitHub

浙公网安备 33010602011771号