
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
2.2.1 常量
在计算机内存中,常量(Constants)用于存储值固定不变的数据,并给出名称。
常量的声明格式如下:

•关键字const用于声明常量的定义。
•name表示常量名。
•方括号表示type部分可选,代表常量的类型。当程序员没有指定该部分时,常量的类型将根据最后的value(值)自动推断得出;当程序员显式指定type时,常量将被限定为特定的数据类型。
•=为赋值符号,用于将value值赋给常量name。一旦完成赋值,名称为name的常量就有了值,且不会改变。
1.单一常量声明
示例1 单一常量声明及使用(代码文件:const.go)

在GoLand代码编辑框中单击代码左侧的绿色三角形按钮,执行代码的编译运行,结果如下:

说明
常量的类型只能是基本数据类型,即布尔型、数字型(整型、浮点型和复数型)和字符串型。
2.批量常量声明
示例2 批量常量声明及使用(代码文件:const.go)

从上述定义中可以发现,在批量声明常量时,在关键字const后面使用圆括号包裹连续声明的多个常量。其运行结果如下:

3.常量生成器iota
使用关键字iota可以为批量常量进行连续增1赋值。iota初始值为0。
示例3 iota批量连续赋值(代码文件:const.go)

上述代码的运行结果如下:
