常量组的定义
如果程序需要用到大量值相同的常量,我们可以直接定义常量组。
在定义常量组时,若不提供初始值,则表示将使用上行的表达式。
package main
import "fmt"
const (
a = 3.14
b
c
d = 100
)
func main() {
fmt.Println("a:",a)
fmt.Println("b:",b)
fmt.Println("c:",c)
fmt.Println("d:",d)
}
执行结果如下:
a: 3.14
b: 3.14
c: 3.14
d: 100
常量枚举
枚举通常针对一个有穷序列集而言,一个集的枚举就是列出有穷序列集的所有成员。
Go语言现阶段还没有枚举,但是我们可以使用一种特殊常量“iota”来模拟枚举。
iota在const关键字出现时被重置为0,const中每新增一行常量声明,将使iota进行一次计数,我们可以简单地将iota理解为const语句块中的行索引。
package main
import "fmt"
func main() {
const(
a = iota //0
b //沿用上一行iota,此时iota=1,b=1
c = "Hello world" //iota += 1,iota=2
d //沿用上一行的"Hello world",d="Hello
world",iota += 1,iota=3
e = iota //iota += 1,iota=4
)
fmt.Println("a:",a)
fmt.Println("b:",b)
fmt.Println("c:",c)
fmt.Println("d:",d)
fmt.Println("e:",e)
}
执行结果如下:
a: 0
b: 1
c: Hello world
d: Hello world
e: 4