Skip to content

Commit

Permalink
iota
Browse files Browse the repository at this point in the history
  • Loading branch information
guyan0319 committed Aug 25, 2022
1 parent 61b8a04 commit fdf9e76
Show file tree
Hide file tree
Showing 2 changed files with 141 additions and 0 deletions.
140 changes: 140 additions & 0 deletions zh/2.16.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@



## Go 之iota

iota是一个常量计数器,一般在常量表达式中使用,可以理解为const定义常量的行数的索引,注意是行数

## 使用场景
主要应用在需要枚举的地方

示例1
````
package main
import "fmt"
const (
NoPay = iota // 订单未支付 0
Paid // 已支付 1
Cancelled // 已取消 2
PendIng // 未发货 3
Delivered // 已发货 4
Received // 已收货 5
)
func main() {
fmt.Println(NoPay,Received)
}
````
示例2
````
package main
import "fmt"
const (
_ = 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)
)
func main() {
fmt.Println(KB,MB,GB)
}
````
## iota不等于0,它代表const语句块中的行索引,只有在第一行时才等于0,每出现一次常量,其所代表的数字会自动增加1
示例1:
````
package main
import "fmt"
const (
a = iota
b
c = "c"
d
e = iota
f
)
func main() {
fmt.Println(a, b, c, d, e, f) //0 1 c c 4 5
}
````
示例2:
````
package main
import "fmt"
const (
b="b"
a = iota
)
func main() {
fmt.Println(b,a)//b 1
}
````
## 在每一个const关键字出现时被重置为0
示例:
````
package main
import "fmt"
const (
a = iota
b
)
const (
c = iota
)
func main() {
fmt.Println(a,b,c)//0 1 0
}
````
## 支持移位运算

````
package main
import "fmt"
const (
a = 1 << iota
b
c
d
e
f
)
func main() {
fmt.Println(a, b, c, d, e, f) //1 2 4 8 16 32
}
````

## 总结
使用iota能保证一组常量的唯一性,避免无效值,提高代码可维护性。





## links

- [目录](/zh/preface.md)
- 上一节:
- 下一节:

1 change: 1 addition & 0 deletions zh/preface.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
- 2.13 [Go 类型](/zh/2.13.md)
- 2.14 [Go 之 interface接口理解](/zh/2.14.md)
- 2.15 [Go之time包用法](/zh/2.15.md)
- 2.16 [Go 之iota](/zh/2.16.md)

#### 3 字符处理

Expand Down

0 comments on commit fdf9e76

Please sign in to comment.