Go學習:常量報錯 const initializer is not a constant

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

 

參考文獻:

《Runtime And Compiletime Constants In C#》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章