go 枚举实现

172 阅读1分钟

很多业务我们可能会用到枚举这样的类型,但是golang没有专门的语法,那么我们一般使用的时候只需要给一个int类型取一个别名,再加上iota就可以轻松的实现,要不然如果你只是定义常量的时候两个常量仍然是可以比较的

package main

import "fmt"

type Season int

const (
	Summer Season = iota + 1

	Autumn

	Winter

	Spring
)

type ArticleState int

const (
	Draft int = iota + 1

	Published

	Deleted
)

func checkArticleState(state ArticleState) bool {

	// ...
	return false

}

func main() {

	// 两个操作数类型不匹配,编译错误

	fmt.Println(Autumn == Draft)

	// 参数类型不匹配,但是因为 ArticleState 底层的类型是 int 所以传递 int 的时候会发生隐式类型转换,所以不会报错

	checkArticleState(100)

}