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)
}
自己動手試一試 »