Go語言支持字符,字符串,布爾和數(shù)值的常量。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.com/go/go_environment.html
const
關(guān)鍵字用來聲明一個(gè)常量值。const
語句可以出現(xiàn)在var
語句的任何地方。常量表達(dá)式以任意精度執(zhí)行算術(shù)運(yùn)算。數(shù)字常量在給定一個(gè)數(shù)字常量之前不指定類型,例如通過顯式轉(zhuǎn)換。
可以通過在需要一個(gè)數(shù)字的上下文中使用它來給予數(shù)字一個(gè)類型,例如,變量賦值或函數(shù)調(diào)用。 例如,這里math.Sin
期望一個(gè)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))
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run constants.go
constant
6e+11
600000000000
-0.28470407323754404