go 常量報錯 const initializer is not a constant


Go的常量const是屬於編譯時期的常量,即在編譯時期就可以完全確定取值的常量。只支持數字,字符串和布爾,及上述類型的表達式。而切片,數組,正則表達式等等需要在運行時分配空間和執行若干運算才能賦值的變量則不能用作常量。這一點和Java,Nodejs(javascript)不同。Java的final和Nodejs的const代表的是一次性賦值的變量,本質上還是變量,只是不允許后續再做修改,任意類型都可以,可以在運行時賦值。

可以這樣類比:Go的常量對應於C#的const,而Java,Nodejs的常量對應於C#的readonly。

 


  1. package main
  2.  
  3. import(
  4. "regexp"
  5. )
  6.  
  7. //正確
  8. const R1 = 1
  9. const R2 = 1.02
  10. const R3 = 1 * 24 * 1.03
  11. const R4 = "hello" + " world"
  12. const R5 = true
  13.  
  14. //錯誤: const initializer ... is not a constant
  15. const R6 = [5]int{1,2,3,4,5}
  16. const R7 = make([]int,5)
  17. const R8 = regexp.MustCompile(`^[a-zA-Z0-9_]*$`)
  18.  
  19. func main(){
  20.  
  21. }

     

編譯報錯:
 
  1. ./checkconst. go:15:7: const initializer [5]int literal is not a constant
  2. ./checkconst. go:16:7: const initializer make([]int, 5) is not a constant
  3. ./checkconst. go:17:7: const initializer regexp.MustCompile("^[a-zA-Z0-9_]*$") is not a constant

轉載:https://blog.csdn.net/pengpengzhou/article/details/105288976


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM