概述
将变量的值一一列举出来,变量只限于列举出来的值的范围内取值
Go语言中没有枚举这种数据类型的,但是可以使用const配合iota模式来实现
一、普通枚举
1
2
3
4
5
6
|
const (
cpp = 0
java = 1
python = 2
golang = 3
)
|
二、自增枚举
iota只能在常量的表达式中使用
1
|
fmt.Println(iota) //undefined: iota
|
它默认开始值是0,const中每增加一行加1
1
2
3
4
5
|
const (
a = iota //0
c //1
d //2
)
|
每次 const 出现时,都会让 iota 初始化为0
1
2
3
4
5
|
const d = iota // a=0
const (
e = iota //b=0
f //c=1
)
|
如果中断iota,必须显式恢复!!!
1
2
3
4
5
6
7
|
const (
Low = iota //0
Medium //1
High = 100 //100
Super //100
Band = iota //4
)
|
如果是同一行,值都一样
1
2
3
4
5
|
const (
i = iota
j1, j2, j3 = iota, iota, iota
k = iota
)
|
可跳过的值
1
2
3
4
5
6
7
|
const (
k1 = iota // 0
k2 // 1
_ //2
_ //3
k3 // 4
)
|
中间插入一个值
1
2
3
4
5
6
7
|
const (
Sun = iota //Sun = 0
Mon // Mon = 1
Tue = 7 //7
Thu = iota // 3
Fri //4
)
|
注意
- iota 必须配合const 使用,否则undefined: iota
- 每次 const 出现时,都会让 iota 初始化为0
- 如果是同一行,值都一样
代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
package main
import "fmt"
func main() {
//普通枚举
const (
cpp = 0
java = 1
python = 2
)
fmt.Printf("cpp=%d java=%d python=%d\n", cpp, java, python) //a=0 b=1 c=2
//1.iota只能在常量的表达式中使用
//fmt.Println(iota) //undefined: iota
//2.它默认开始值是0,const中每增加一行加1
const (
a = iota //0
b //1
c //2
)
fmt.Printf("a=%d b=%d c=%d\n", a, b, c) //a=0 b=1 c=2
//3.每次 const 出现时,都会让 iota 初始化为0
const d = iota // a=0
const (
e = iota //b=0
f //c=1
)
fmt.Printf("d=%d e=%d f=%d\n", d, e, f) //d=0 e=0 f=1
//4.如果中断iota,必须显式恢复!!!
const (
Low = iota //0
Medium //1
High = 100 //100
Super //100
Band = iota //4
)
//Low=0 Medium=1 High=100 Super=100 Band=4
fmt.Printf("Low=%d Medium=%d High=%d Super=%d Band=%d\n", Low, Medium, High, Super, Band)
//5.如果是同一行,值都一样
const (
i = iota
j1, j2, j3 = iota, iota, iota
k = iota
)
//i=0 j1=1 j2=1 j3=1 k=2
fmt.Printf("i=%d j1=%d j2=%d j3=%d k=%d\n", i, j1, j2, j3, k)
//6.可跳过的值
const (
k1 = iota // 0
k2 // 1
_ //2
_ //3
k3 // 4
)
// k1=0 k2=1 k3=4
fmt.Printf("k1=%d k2=%d k3=%d \n", k1, k2, k3)
//7.中间插入一个值
const (
Sun = iota //Sun = 0
Mon // Mon = 1
Tue = 7 //7
Thu = iota // 3
Fri //4
)
//Sun=0 Mon=1 Tue=7 Thu=3 Fri=4
fmt.Printf("Sun=%d Mon=%d Tue=%d Thu=%d Fri=%d\n", Sun, Mon, Tue, Thu, Fri)
}
|
以上就是Go语言基础枚举的用法及示例详解的详细内容,更多关于Go语言枚举的资料请关注服务器之家其它相关文章!
原文链接:https://blog.csdn.net/guofeng93/article/details/90766400