go语言支持的常量有字符型,字符串型,布尔型和数字型。
用const关键字来定义常量。
能有var语句的地方,就能有const语句。
常量表达式能以任意精度进行计算。常量是没有类型的,除非有语句给出了,例如强制类型转换。
数字常量在上下文需要类型时候,其类型会被自动加上。比如说变量赋值或者函数调用中。本示例中的math.Sin(n),sin
函数需要一个int64类型,n会被自动转换成int64.
1
2
3
4
5
6
7
8
9
10
11
12
|
package main
import "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
原文链接: https://gobyexample.com/constants