Go语言学习-const的使用
基本介绍
1. 常量不能修改
const类似于java中的常量声明,看看基本语法
const name = "zs"
相当于定义个name常量,这个name是不能被修改的
当我们尝试去修改一个const 修饰的常量时:
// Cannot assign to name,下面就是无法修改常量值
name = "ls"
这个时候编译器时会报错的,会给出提示:Cannot assign to name
2. 常量必须初始化
看下这个声明:
// Missing value in the const declaration
const weight float64
这种情况也是不允许存在的,编译器会提示报错,const 声明的变量需要初始化
3. const配合iota使用
// iota,必须和const一起使用,iota是按行数增加的
const (
// iota = 0,然后依次往下递增
age1 = iota
// iota = 1
age2
// iota = 2
age3
)
iota :可以理解行计数器,它时从 0 开始递增的,每一行对应一个值,跟每行有几个变量没什么关系;
const (
// 这里 a, b都在一行,所以 iota的值都是一样的
a, b = iota + 1, iota + 2 // a = 1, b = 2
c, d // c = 2, d = 3
e, f // e = 3, f = 4
g, h = iota * 1, iota * 2 // g = 3, h = 6
i, j // i = 4, j = 8
)
这段代码可以验证,iota 的值与每行有多少变量无关;
全部代码
package main
import "fmt"
// 相当于定义了一个常量值
const name = "zs"
// Missing value in the const declaration
// const weight float64
// iota,必须和const一起使用,iota是按行数增加的
const (
// iota = 0,然后依次往下递增
age1 = iota
// iota = 1
age2
// iota = 2
age3
)
const (
// 这里 a, b都在一行,所以 iota的值都是一样的
a, b = iota + 1, iota + 2 // a = 1, b = 2
c, d // c = 2, d = 3
e, f // e = 3, f = 4
g, h = iota * 1, iota * 2 // g = 3, h = 6
i, j // i = 4, j = 8
)
func main() {
fmt.Println(name)
// Cannot assign to name,下面就是无法修改常量值
// name = "ls"
fmt.Println("age1 =", age1, " age2 =", age2, " age3 =", age3)
fmt.Println("a =", a, " b =", b)
fmt.Println("c =", c, " d =", d)
fmt.Println("e =", e, " h =", h)
fmt.Println("i =", i, " j =", j)
}
输出结果:
zs
age1 = 0 age2 = 1 age3 = 2
a = 1 b = 2
c = 2 d = 3
e = 3 h = 6
i = 4 j = 8