10. 常量 与 数值常量

常量的定义与变量类似,只是需要使用 const 关键字。
常量可以是字符、字符串、布尔型、数字型的值。
需要注意的是,常量不可以使用 := 语法定义。

package main

import(
    "fmt"
)

const Pi = 3.14
func main(){
    const World = "厚土"
    fmt.Println("Hello", World)
    fmt.Println("Happy", Pi, "Day")

    const Truth = true
    fmt.Println("Go rules?", Truth)
}

运行结果是

Hello 厚土
Happy 3.14 Day
Go rules? true

数值常量是高精度的 值。
未指定数据类型的常量,由上下文来决定其类型。

完整代码

package main

import(
    "fmt"
)
const(
    Big = 1 <<100
    Small = Big >> 99
)

func needInt(x int) int  {
    return x * 10 + 1
}
func needFloat(x float64) float64  {
    return x * 0.1
}
func main(){
    //fmt.Println(Big)
    fmt.Println("Small is",Small)
    fmt.Println("needInt Small is",needInt(Small))
    fmt.Println("needFloat Small is",needFloat(Small))
    fmt.Println("needFloat Big is",needFloat(Big))
    //fmt.Println(needInt(Big))
}

你可以试着把主函数中的注释符号去掉,看看效果。
你会发现Big超出了int的最大值边界。

你可能感兴趣的:(10. 常量 与 数值常量)