常量指的是在编译期间已知的且不可改变的数据类型,常量可以是数值类型、浮点型、复合类型、布尔类型、字符串类型,在go中任何编译器后试图改变常量的操作都会导致编译报错。
定义常量
在go中我们可以使用const来定义常量,以下是常见的击中定义方式
package _constconst Pi float64 = 3.14159265358979323846const zero = 0.0 // 无类型浮点常量const ( // 通过一个 const 关键字定义多个常量,和 var 类似size int64 = 1024eof = -1 // 无类型整型常量)const u, v float32 = 0, 3 // u = 0.0, v = 3.0,常量的多重赋值const a, b, c = 3, 4, "foo" // a = 3, b = 4, c = "foo", 无类型整型和字符串常量
预定义常量
go中预定义的常量有 true,false,iotaiota比较特殊,它是一个可以被编译器修改的常量。在编译期间每次const关键字出现时iota都会被重置为0,直到下一个const出现前,每出现一次iota都会递增。
package mainimport "fmt"const (a1 = iotaa2 = iotaa3 = iota)const (b1 = iota * 2b2 = iota * 2b3 = iota * 2)const (c1 = iota * 3c2c3)func main() {fmt.Printf("a1 is %d \n", a1)fmt.Printf("a2 is %d \n", a2)fmt.Printf("a3 is %d \n", a3)fmt.Printf("b1 is %d \n", b1)fmt.Printf("b2 is %d \n", b2)fmt.Printf("b3 is %d \n", b3)fmt.Printf("c1 is %d \n", c1)fmt.Printf("c2 is %d \n", c2)fmt.Printf("c2 is %d \n", c3)}
枚举
go中并没有其他语言类似的enum 关键字,而是通过,const后跟一对圆括号定义一组常量的方式来实现枚举。
const (Sunday = iotaMondayTuesdayWednesdayThursdayFridaySaturdaynumberOfDays)
常量作用域
跟变量一致,以大写开头的常量是可以在当前包和外部包进行访问的(public),以小写开头的常量只能在当前包中进行访问。
