1 定义
与其他语言一样,Go中的常量一旦被赋值就不能再被修改为其他值。
通过关键字const定义常量
语法
//关键字 常量名 常量值
const age 10
测试
package main
import "fmt"
func main() {
const a = 55
a = 56 // cannot assign to a (untyped int constant 55)
fmt.Println(a)
}
常量的值会在编译的时候确定。因为函数调用发生在运行时,所以不能将函数的返回值赋值给常量。
package main
import (
"fmt"
"math"
)
func main() {
const a = math.Sqrt(4) // math.Sqrt(4) (value of type float64) is not constant
fmt.Println(a)
}
2 字符串常量
语法
// 关键字 变量名 变量类型 变量值
const name type = value
测试
package main
import "fmt"
func main() {
const hello string = "hello world"
// hello = "1234" cannot assign to hello (constant "hello world" of type string)
fmt.Printf("hello type is %T, hello : %s", hello, hello)
}