forked from guyan0319/golang_development_notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
141 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
- 上一节: | ||
- 下一节: | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters