1.1.1. 一、常量的说明:
1、常量使用const声明。
2、常量定义的时候必须初始化。常量不能修改。
3、只有bool、数值类型(int、float系列)、string类型。才能声明为常量。
4、声明常量的语法:const 常量名 [类型] = 常量值
5、和变量一样,首字母大小写可以控制访问范围。
1.1.2. 二、常量的写法:
1、一次声明一个。
const num1 int = 88
const num2 int = 9/3 //正确,9/3 是常量
const num3 int = num2/3 //正确,常量除以常量,也是常量
const str = "你好" //类型推导
2、一次声明多个。
//一次声明多个
const (
name = "张三" //类型推导
age int = 18
pwd = "123"
pwd2 // pwd2 等于 pwd
)
func main() {
fmt.Println(pwd,pwd2,pwd == pwd2) //123 123 true
}
注意:pwd2 等于 pwd。
3、使用iota。
func main() {
//a = iota,表示a等于0,后面b、c、d不给值,依次加1.
const (
a = iota
b
c
d
)
fmt.Println(a,b,c,d) //0 1 2 3
}
iota的作用是累加。上面的代码相当于:a = iota,表示a等于0,后面b、c、d等于iota,依次加1。
const ( a = iota b = iota c = iota d = iota )
如果把 iota写在一行,只累加一次:
const (
a = iota
b = iota
c,d = iota,iota
)
fmt.Println(a,b,c,d) //0 1 2 2
c,d = iota,iota
这个写在一行,那iota就只累加1。