Update 04.3.md 完善 iota 的重要特性描述以及示例 (#770)

Co-authored-by: ᴜɴᴋɴᴡᴏɴ <u@gogs.io>
This commit is contained in:
Snile
2020-08-16 19:38:48 +08:00
committed by GitHub
parent 3f1fc7097b
commit e608c2672f

View File

@@ -76,13 +76,43 @@ const (
)
```
第一个 `iota` 等于 0每当 `iota` 在新的一行被使用时,它的值都会自动加 1;所以 `a=0, b=1, c=2` 可以简写为如下形式:
第一个 `iota` 等于 0每当 `iota` 在新的一行被使用时,它的值都会自动加 1,并且没有赋值的常量默认会应用上一行的赋值表达式:
```go
// 赋值一个常量时,之后没赋值的常量都会应用上一行的赋值表达式
const (
a = iota
b
c
a = iota // a = 0
b // b = 1
c // c = 2
d = 5 // d = 5
e // e = 5
)
// 赋值两个常量iota 只会增长一次,而不会因为使用了两次就增长两次
const (
Apple, Banana = iota + 1, iota + 2 // Apple=1 Banana=2
Cherimoya, Durian // Cherimoya=2 Durian=3
Elderberry, Fig // Elderberry=3, Fig=4
)
// 使用 iota 结合 位运算 表示资源状态的使用案例
const (
Open = 1 << iota // 0001
Close // 0010
Pending // 0100
)
const (
_ = iota // 使用 _ 忽略不需要的 iota
KB = 1 << (10 * iota) // 1 << (10*1)
MB // 1 << (10*2)
GB // 1 << (10*3)
TB // 1 << (10*4)
PB // 1 << (10*5)
EB // 1 << (10*6)
ZB // 1 << (10*7)
YB // 1 << (10*8)
)
```
@@ -92,35 +122,6 @@ const (
当然,常量之所以为常量就是恒定不变的量,因此我们无法在程序运行过程中修改它的值;如果你在代码中试图修改常量的值则会引发编译错误。
引用 `time` 包中的一段代码作为示例:一周中每天的名称。
```go
const (
Sunday = iota
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
)
```
你也可以使用某个类型作为枚举常量的类型:
```go
type Color int
const (
RED Color = iota // 0
ORANGE // 1
YELLOW // 2
GREEN // ..
BLUE
INDIGO
VIOLET // 6
)
```
## 链接