宣告一個常量
常量宣告為變數,但使用 const
關鍵字:
const Greeting string = "Hello World"
const Years int = 10
const Truth bool = true
與變數一樣,以大寫字母開頭的名稱將被匯出( 公共 ),以小寫字母開頭的名稱則不會。
// not exported
const alpha string = "Alpha"
// exported
const Beta string = "Beta"
除了無法更改值之外,常量可以像任何其他變數一樣使用。這是一個例子:
package main
import (
"fmt"
"math"
)
const s string = "constant"
func main() {
fmt.Println(s) // constant
// A `const` statement can appear anywhere a `var` statement can.
const n = 10
fmt.Println(n) // 10
fmt.Printf("n=%d is of type %T\n", n, n) // n=10 is of type int
const m float64 = 4.3
fmt.Println(m) // 4.3
// An untyped constant takes the type needed by its context.
// For example, here `math.Sin` expects a `float64`.
const x = 10
fmt.Println(math.Sin(x)) // -0.5440211108893699
}