您的位置:首页 > 编程语言 > Go语言

<3> go 枚举

2015-11-19 18:14 513 查看
在go语言中,没有直接支持枚举的关键字,也就造成go没有直接枚举的功能。但是go提供另一种方法来实现枚举,那就是const+iota

[code]// 实现枚举例子

type State int

// iota 初始化后会自动递增
const (
    Running State = iota // value --> 0
    Stopped              // value --> 1
    Rebooting            // value --> 2
    Terminated           // value --> 3
)

func (this State) String() string {
    switch this {
    case Running:
        return "Running"
    case Stopped:
        return "Stopped"
    default:
        return "Unknow"
    }
}

func main() {
    state := Stopped
    fmt.Println("state", state)
}
// 输出 state Running
// 没有重载String函数的情况下则输出 state 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: