暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Go语言之旅:常量

小菜学编程 2018-08-16
209

常量( constants
)申明与变量一样,只不过换成 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)
}

数值常量

数值常量是高精度数值。 常量虽然没有指定类型,却可以根据实际情况采用合适类型,保证精度够用。

试试输出 needInt(Big)

package main

import "fmt"

const (
    // Create a huge number by shifting a 1 bit left 100 places.
    // In other worlds, the binary number that is 1 followed by 100 zeros.
    Big = 1 << 100

    // Shift it right again 99 places, so we end up with 1<<1, or 2.
    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(needInt(Small))
    fmt.Println(needFloat(Small))
    fmt.Println(needFloat(Big))
}

类型

到这为止,我们介绍的常量申明方式是无类型的( untyped ),语法结构如下:

无类型常量申明

其实, Go 语言还支持另一种申明方式—— 指定类型 常量( typed constants ),对应的语法结构则是:

指定类型常量申明

非常简单明了,例子就不单独举了。

下一步

下一节 我们一起来看看 Go 语言 for 语句 。

订阅更新,获取更多学习资料,请关注我们的 微信公众号 :

小菜学编程


文章转载自小菜学编程,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论