Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go常量实例
Go常量实例
作者:--    发布时间:2019-11-20

go语言支持字符,字符串,布尔和数值的常量。

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册