GO 学习之常量与iota
常量
相对于变量,常量是恒定不变的值,多用于定义程序运行期间不会改变的那些值。 常量的声明和变量声明非常类似,只是把var换成了const,常量在定义的时候必须赋值。
举例:
package main
import "fmt"
// 单个声明常量
const pi = 3.1415926
// 批量声明常量
const (
statusOK = 200
notFund = 404
)
const (
n1 = 100
n2
n3
)
func main() {
fmt.Println(pi)
fmt.Println(statusOK)
fmt.Println(notFund)
fmt.Println(n1, n2, n3)
}
iota
iota是go语言的常量计数器,只能在常量的表达式中使用。
iota在const关键字出现时将被重置为0。const中每新增一行常量声明将使iota计数一次(iota可理解为const语句块中的行索引)。 使用iota能简化定义,在定义枚举时很有用。
package main
import "fmt"
// iota const 中每新增一行常量声明将使iota计数一次(+1)
// 类似枚举
const (
a1 = iota // 0
a2 = iota // 1
a3 = iota // 2
)
const (
b1 = iota // 0
b2 = iota // 1
_ = iota // 2
b3 = iota // 3
)
const (
c1 = iota // 0
c2 = 100 // 100
c3 = iota // 2
)
const (
d1,d2 = iota + 1, iota + 2 // 1 2
d3,d4 = iota + 1 , iota + 2 // 2 3
)
func main() {
fmt.Println(a1, a2, a3)
fmt.Println(b1, b2, b3)
fmt.Println(c1, c2, c3)
fmt.Println(d1, d2, d3,d4)
}

浙公网安备 33010602011771号