Go 支援字串、字元、布林和數值的常數。
package main
import ( "fmt" "math" )
const 宣告常數值。
const
const s string = "constant"
func main() { fmt.Println(s)
const 語句可以在任一可放 var 語句的地方出現。
var
const n = 500000000
常數運算可以進行任意精度的算術。
const d = 3e20 / n fmt.Println(d)
數字常數在賦予型別之前沒有型別,例如明確轉換。
fmt.Println(int64(d))
數字可在需要型別的環境中給定型別,例如變數指定或函式呼叫。例如,這裡的 math.Sin 預期為 float64。
math.Sin
float64
fmt.Println(math.Sin(n)) }
$ go run constant.go constant 6e+11 600000000000 -0.28470407323754404
下一個範例:For。
by Mark McGranaghan 和 Eli Bendersky | 原始碼 | 授權條款