【金秋打卡】第14天 Go开发工程师全新版 3-3
2022/11/9 3:24:05
本文主要是介绍【金秋打卡】第14天 Go开发工程师全新版 3-3,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
课程名称: Go开发工程师全新版
课程章节: 3-3 iota 的使用细节
课程讲师: bobby
课程内容:
iota:go 中关键字,是一个特殊常量, 可以认为是一个可以被编译器修改的常量,默认类型 int
iota 可以看做一个计数器,从 0 开始计数,只能在定义常量时给常量赋值使用,如下:
package main import "fmt" func main() { const { ERR1 = iota //1, 从 0 开始计数 ERR2 = iota // 2 ERR3 = iota // 3 } fmt.Println(ERR1, ERR2, ERR3) // 简写 const { ERR1 = iota ERR2 ERR3 } fmt.Println(ERR1, ERR2, ERR3) // 可以给 iota 后面 + 1 const { ERR1 = iota + 1 //1, 从 1 开始计数 ERR2 // 2 ERR3 // 3 } fmt.Println(ERR1, ERR2, ERR3) }
注意事项
-
如果中断了iota那么必须显式的恢复, 后续会自动递增
package main import "fmt" func main() { const ( ERR1 = iota + 1 ERR2 //iota +1 ERR25 = "ha" // 值为 ha。虽然中断了 iota,但 iota 内部仍然会增加计数器 iota +1 ERR3 // 值为 ha,iota +1 ERR31 // 值为 ha,iota +1 ERR32 // 值为 ha,iota +1 ERR33=100 // 值为 100,这里的值不影响iota,因为iota是内部计数的,iota +1 ERR4 = iota // 值为 7,这里需要显示恢复 iota,后续才会自动递增 ERR5 ) fmt.Println(ERR1, ERR2, ERR25, ERR3, ERR4, ERR5) }
-
自增类型默认是int类型
-
iota能简化 const 类型的定义
-
每次出现const的时候, iota初始化为0
package main import "fmt" func main() { const ( ERR1 = iota + 1 // 1 ERR2 // 2 ERR3 // 3 ERR4 // 4 ) const ( NEWIOTA1 = iota // 0, iota初始化为0 ) fmt.Println(ERR1, ERR2, ERR3, ERR4) // 1 2 3 4 fmt.Println(NEWIOTA1) // 0 }
课程收获:
了解 iota 可以让常量从0开始自增长
这篇关于【金秋打卡】第14天 Go开发工程师全新版 3-3的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-01got an unexpected keyword argument
- 2024-03-30维多利亚的秘密 golang入坑系统
- 2024-03-29mongodb sort by date
- 2024-03-29go swagger
- 2024-03-25mongodb cdc
- 2024-03-25how to use go in vscode
- 2024-03-22mongooseserverselectionerror: connect econnrefused ::1:27017
- 2024-03-21pymongo insert_many
- 2024-03-18projection mongodb
- 2024-03-14clickhouse-go