概念
常量用于定义不可被修改的值,需要在编译过程中进行计算,只能是基础数据类型:布尔、 数值型、字符串。
使用 const 进行常量声明:const 常量名称 类型 = 值
常量初始化
指定数据类型
// 演示常量声明 & 使用(指定数据类型)package mainimport ("fmt")func main () {const a int = 123const b float64 = 3.14const c string = "isconst"const d bool = truefmt.Println("a =",a ,"b =",b ,"c =",c ,"d =", d)}
类型推导
声明时,不指定数据类型,而是让编译器通过常量的值进行类型推导
// 演示通过类型推导申明常量package mainimport ("fmt")func main () {const a = 123const b = 3.14const c = "isconst"const d = truefmt.Printf("a 的数据类型是%T\n",a)fmt.Printf("b 的数据类型是%T\n",b)fmt.Printf("c 的数据类型是%T\n",c)fmt.Printf("d 的数据类型是%T\n",d)}/*代码运行结果展示a 的数据类型是intb 的数据类型是float64c 的数据类型是stringd 的数据类型是bool*/
批量声明
// 演示批量声明常量package mainimport ("fmt")func main (){const (a = 123b = 3.14c = "isconst"d = true)fmt.Println(a, b, c, d)}
省略常量值
const同时声明多个常量时,如果省略了值, 则表示和上面一行的值相同
// 演示批量声明常量并省略常量值package mainimport ("fmt")func main (){const (a = 123bcd)fmt.Println("a =", a, "\nb =", b, "\nc =", c, "\nd =", d)}/*代码运行结果展示a = 123b = 123c = 123d = 123*/
“枚举” iota
GO中没有枚举变量,但是可以通过 const + iota 实现同样的功能
iota是Go语言中的常量计数器,只能在常量表达式中使用。 iota在const关键字出现时将被重置为0。
const中每新增一行常量声明将使iota计数一次。 使用iota能简化定义。
iota 的初始值为0,后续每次加1
// 演示通过const + iota 实现枚举功能// 要求定义常量 a、b、c、d 分别为 1、2、3、4package mainimport ("fmt")func main(){const(a = 1 + iotabcd)// 相当于a、b、c、d 都等于 1 + iotafmt.Println("a =", a, "\nb =", b, "\nc =", c, "\nd =", d)}/*代码运行结果展示a = 1b = 2c = 3d = 4*/
