Go 常量
Go 常量
如果一个变量应该有一个固定且不可更改的值,您可以使用 const
关键字。
The const
keyword declares the variable as "constant", which means that it is unchangeable and read-only.
语法
const CONSTNAME type = value
注意: 常量的必须在声明时赋值。
声明常量
Here is an example of declaring a constant in Go
常量规则
- Constant names follow the same naming rules as variables
- 常量名称通常使用大写字母(以便于识别和区分变量)
- 常量可以在函数内部或外部声明
常量类型
There are two types of constants
- Typed constants
- Untyped constants
已声明类型的常量
Typed constants are declared with a defined type
未声明类型的常量
Untyped constants are declared without a type
注意: 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)
}
结果
./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)
}
自己动手试一试 »