本篇内容主要讲解“Golang枚举类型的基础用法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Golang枚举类型的基础用法”吧!
为了下面讲解方便,这里使用 go modules 的方式先建立一个简单工程。
~/Projects/go/examples
➜ mkdir enum
~/Projects/go/examples
➜ cd enum
~/Projects/go/examples/enum
➜ go mod init enum
go: creating new go.mod: module enum
~/Projects/go/examples/enum
➜ touch enum.go
const + iota
以 启动、运行中、停止 这三个状态为例,使用 const 关键来声明一系列的常量值。在 enum.go 中写上以下内容:
package main
import "fmt"
const (
Running int = iota
Pending
Stopped
)
func main() {
fmt.Println("State running: ", Running)
fmt.Println("State pending: ", Pending)
fmt.Println("State Stoped: ", Stopped)
}
保存并运行,可以得到以下结果,
~/Projects/go/examples/enum
➜ go run enum.go
State running: 0
State pending: 1
State Stoped: 2
在说明发生了什么之前,我们先看来一件东西,iota。相比于 c、java,go 中提供了一个常量计数器,iota,它使用在声明常量时为常量连续赋值。
比如这个例子,
const (
a int = iota // a = 0
b int = iota // b = 1
c int = iota // c = 2
)
const d int = iota // d = 0
在一个 const 声明块中,iota 的初始值为 0,每声明一个变量,自增 1。以上的代码可以简化成:
const (
a int = iota // a = 0
b // b = 1
c // c = 2
)
const d int = iota // d = 0
设想一下,如果此时有 50 或者 100 个常量数,在 c 和 java 语言中写出来会是什么情况。
关于 iota,有更多的具体的技巧(例如跳数),详细请看官方定义 iota。
通过使用 const 来定义一连串的常量,并借助 iota 常量计数器,来快速的为数值类型的常量连续赋值,非常方便。虽然没有了 enum 关键字,在这种情况下发现,是多余的,枚举本质上就是常量的组合。
当然,你可以使用以下方式,来更接近其它语言的 enum,
// enum.go
...
type State int
const (
Running State = iota
Pending
Stopped
)
...
把一组常量值,使用一个类型别名包裹起来,是不是更像其它语言中的 enum {} 定义了呢?
你还可以将上面的例子改为:
// enum.go
...
type State int
const (
Running State = iota
Pending
Stopped
)
func (s State) String() string {
switch s {
case Running:
return "Running"
case Pending:
return "Pending"
case Stopped:
return "Stopped"
default:
return "Unknown"
}
}
...
为定义的枚举类型加上 String 函数,运行结果如下:
~/Projects/go/examples/enum
➜ go run enum.go
State running: Running
State pending: Pending
State Stoped: Stopped
到此,相信大家对“Golang枚举类型的基础用法”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。