If a variable should have a fixed value that cannot be changed, you can use the const
keyword.
The const
keyword declares the variable as "constant", which means that it is unchangeable and read-only.
const
CONSTNAME type =
value
Note: The value of a constant must be assigned when you declare it.
Here is an example of declaring a constant in Go:
package main
import ("fmt")
const PI = 3.14
func main() {
fmt.Println(PI)
}
Try it Yourself »
There are two types of constants:
Typed constants are declared with a defined type:
package main
import ("fmt")
const A int = 1
func main() {
fmt.Println(A)
}
Try it Yourself »
Untyped constants are declared without a type:
Note: In this case, the type of the constant is inferred from the value (means the compiler decides the type of the constant, based on the value).
When a constant is declared, it is not possible to change the value later:
package main
import ("fmt")
func main() {
const A = 1
A = 2
fmt.Println(A)
}
Result:
./prog.go:8:7: cannot assign to A
Multiple constants can be grouped together into a block for readability:
package main
import ("fmt")
const (
A int = 1
B = 3.14
C = "Hi!"
)
func main() {
fmt.Println(A)
fmt.Println(B)
fmt.Println(C)
}
Try it Yourself »
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!