常量用来表示固定值,如5
、-89
、"你好"
、67.89
等等。
考虑以下代码
var a int = 50
var b string = "I love Go"
在上面的代码中,a
和b
分别赋值50
和"I love Go"
。
关键字const
用于表示诸如50
和"I love Go"
之类的常量。在上面的代码中,尽管没有显式地使用关键字const
,但在内部它们是常量。
常量值不能改变,因此,下面的程序将报错。
package main
func main() {
const a = 55 //常量
a = 89 //报错,常量值不能改变
}
常量值在编译时就已确定,不能把函数返回值赋值给常量,因为函数调用是在运行时进行的。
package main
import (
"fmt"
"math"
)
func main() {
fmt.Println("Hello, playground")
var a = math.Sqrt(4)//正确
const b = math.Sqrt(4)//报错
}
在上面的程序中,a
是一个变量,因此可以将math.Sqrt(4)
函数的结果赋值给它。
b
是一个常量,在编译时就已经确定。函数math.Sqrt(4)
只在运行时执行,因此const b = math.Sqrt(4)
会抛出错误:
error main.go:11: const initializer math.Sqrt(4) is not a constant.