Go的常量const是屬於編譯時期的常量,即在編譯時期就可以完全確定取值的常量。只支持數字,字符串和布爾,及上述類型的表達式。而切片,數組,正則表達式等等需要在運行時分配空間和執行若干運算才能賦值的變量則不能用作常量。這一點和Java,Nodejs(javascript)不同。Java的final和Nodejs的const代表的是一次性賦值的變量,本質上還是變量,只是不允許后續再做修改,任意類型都可以,可以在運行時賦值。
可以這樣類比:Go的常量對應於C#的const,而Java,Nodejs的常量對應於C#的readonly。
-
package main -
-
import(
-
"regexp"
-
)
-
-
//正確
-
const R1 = 1
-
const R2 = 1.02
-
const R3 = 1 * 24 * 1.03
-
const R4 = "hello" + " world"
-
const R5 = true
-
-
//錯誤: const initializer ... is not a constant
-
const R6 = [5]int{1,2,3,4,5}
-
const R7 = make([]int,5)
-
const R8 = regexp.MustCompile(`^[a-zA-Z0-9_]*$`)
-
-
func main(){
-
-
}
編譯報錯:
-
./checkconst. go:15:7: const initializer [5]int literal is not a constant
-
./checkconst. go:16:7: const initializer make([]int, 5) is not a constant
-
./checkconst. go:17:7: const initializer regexp.MustCompile("^[a-zA-Z0-9_]*$") is not a constant
轉載:https://blog.csdn.net/pengpengzhou/article/details/105288976