選單
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

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

示例

package main
import ("fmt")

const PI = 3.14

func main() {
  fmt.Println(PI)
}
自己動手試一試 »

常量規則

  • 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

示例

package main
import ("fmt")

const A int = 1

func main() {
  fmt.Println(A)
}
自己動手試一試 »


未宣告型別的常量

Untyped constants are declared without a type

示例

package main
import ("fmt")

const A = 1

func main() {
  fmt.Println(A)
}
自己動手試一試 »

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

×

聯絡銷售

如果您想將 W3Schools 服務用於教育機構、團隊或企業,請傳送電子郵件給我們
sales@w3schools.com

報告錯誤

如果您想報告錯誤,或想提出建議,請傳送電子郵件給我們
help@w3schools.com

W3Schools 經過最佳化,旨在方便學習和培訓。示例可能經過簡化,以提高閱讀和學習體驗。教程、參考資料和示例會不斷審查,以避免錯誤,但我們無法保證所有內容的完全正確性。使用 W3Schools 即表示您已閱讀並接受我們的使用條款Cookie 和隱私政策

版權所有 1999-2024 Refsnes Data。保留所有權利。W3Schools 由 W3.CSS 提供支援