這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。Go by Example: Constants
Go supports constants of character, string, boolean, and numeric values.
const declares a constant value.
A const statement can appear anywhere a var statement can.
Constant expressions perform arithmetic with arbitrary precision.
A numeric constant has no type until it’s given one, such as by an explicit cast.
A number can be given a type by using it in a context that requires one, such as a variable assignment or function call. For example, here math.Sin expects a float64.
package mainimport "fmt"import "math"const s string = "constant"func main() { fmt.Println(s) const n = 500000000 const d = 3e20 / n fmt.Println(d) fmt.Println(int64(d)) fmt.Println(math.Sin(n))}
譯:
Go 語言支援的常量類型有 characer string 字元型 boolean 波爾型 numeric 數值
用 const關鍵字來聲明一個常量值
一個常量聲明能展現的 、任何一個var聲明的都可以
常量運算式可以展現任意精度的算術運算
一個算術運算式可以沒有類型,直到他被給予一個值,例如通過顯示轉換
一個數可以用它在需要使用一個給定的類型,例如一個變數的賦值或者一個函數的調用。
例如,這裡的math.Sin就是期望是一個float64的類型。
package mainimport "fmt"import "math"const s string = "constant"func main() { fmt.Println(s) const n = 500000000 //定義一個常量 注意這裡的常量類型就是不允許改變了 const d = 3e20 / n //根據科學技術法計算 fmt.Println(d) fmt.Println(int64(d)) fmt.Println(math.Sin(n))}
運行結果
$ go run constant.go
constant
6e+11
600000000000
-0.28470407323754404