Go语言中没有枚举这种数据类型的,但是可以使用const配合iota模式来实现,如果要为枚举添加方法的话还涉及到类型的定义,以及为新建类型添加方法。所以在开始介绍实现go语言的枚举实现之前,我们先来看看类型别名(在Go1.9版本新增的功能,主要用于代码升级、迁移中类型的兼容性问题)和类型定义的区别。
写法对比:
类型别名的写法:
type TypeAlias = Type // TypeAlias只是Type的别名,本质上TypeAlias和Type是同一个类型。
类型定义的写法:
type TypeNew = Type // TypeNew 是一个新的类型,拥有Type相关的所有属性和方法
通过以下示例来验证以上观点:
package main // 定义包名
import "fmt"
// MyInt 将MyInt 定义为int类型
type MyInt int
// IntAlias 将int 取名为IntAlias
type IntAlias = int
// 为MyInt定义一个add方法
func (a MyInt) add(b int) {
}
// 为IntAlias 定义remove方法,编译报错:cannot define new methods on non-local type int
// func (a