您的位置:首页 > 编程语言 > Go语言

Go语言学习之常量(The way to go)

2017-02-23 00:46 686 查看
生命不止,继续go go go .

上一篇博客《Go语言学习之变量(The way to go)介绍了go中的变量,今天就介绍常量。

const关键字

跟c++中一样,go中同样具有const关键字,来声明常量。

语法是这样的:

const variable type = value;


下面就是简单的常量定义:

const LENGTH int = 10
const WIDTH int = 5


同样可以用块的形式声明一系列常量:

package main

import "fmt"

func main() {
const(
LENGTH int = 10
WIDTH int = 8
)
fmt.Println(LENGTH)
}


结果输出:10

这里你有没有发现一个问题,我们没用使用WIDTH这个常量,但是编译器没有报错。

未使用的常量不会引发编译器错误!!

同样,在声明常量的时候,也可以省略常量的类型,由编译器自动推断:

package main

import "fmt"

const (
Cat  = 10
Dog  = 20
Bird = 30
)

func main() {
// Use our constants.
fmt.Println(Cat)
fmt.Println(Dog)
fmt.Println(Bird)
}


输出:

10

20

30

另外,需要注意,不能给常量进行重新赋值:

const (
Normal = 1
Medium = 2
)

func main() {
Medium = 3
}


错误:cannot assign to Medium

可以一行声明多个常量:

const name, size = "carrot", 100


不能读取常量的地址:

package main

import "fmt"

var x int = 100
const y int = 200

func main() {
fmt.Println(&x, x)
fmt.Println(&y, y)
}


错误:cannot take the address of y

iota关键字

C++中我们使用enum关键字来定义枚举,但是在go中没有这个关键字,但是为我们提供iota关键字。

iota是优雅的自增量!!!!

this is an enumerator for const creation. The Go compiler starts iota at 0 and increments it by one for each following constant. We can use it in expressions.

直接看看代码:

package main

import "fmt"

const (
Low = 5 * iota
Medium
High
)

func main() {
// Use our iota constants.
fmt.Println(Low)
fmt.Println(Medium)
fmt.Println(High)
}


输出:

0

5

10

如果中断iota,必须显示恢复

package main

import "fmt"

const (
Low = iota
Medium
High = 100
Super
Band = iota
)

func main() {
// Use our iota constants.
fmt.Println(Low)
fmt.Println(Medium)
fmt.Println(High)
fmt.Println(Super)
fmt.Println(Band)
}


输出:

0

1

100

100

4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: