Go语言学习之常量(The way to go)
2017-02-23 00:46
691 查看
生命不止,继续go go go .
上一篇博客《Go语言学习之变量(The way to go)介绍了go中的变量,今天就介绍常量。
语法是这样的:
下面就是简单的常量定义:
同样可以用块的形式声明一系列常量:
结果输出:10
这里你有没有发现一个问题,我们没用使用WIDTH这个常量,但是编译器没有报错。
未使用的常量不会引发编译器错误!!
同样,在声明常量的时候,也可以省略常量的类型,由编译器自动推断:
输出:
10
20
30
另外,需要注意,不能给常量进行重新赋值:
错误:cannot assign to Medium
可以一行声明多个常量:
不能读取常量的地址:
错误:cannot take the address of y
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.
直接看看代码:
输出:
0
5
10
如果中断iota,必须显示恢复:
输出:
0
1
100
100
4
上一篇博客《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
相关文章推荐
- Go语言学习之常量(The way to go)
- Go语言学习之time包(获取当前时间戳等)(the way to go)
- Go语言学习之log包(The way to go)
- Go语言学习之image、image/color、image/png、image/jpeg包(the way to go)
- Go语言学习之bufio包(The way to go)
- Go语言学习之字符串(The way to go)
- Go语言学习之net/http包(The way to go)
- Go语言学习之指针(The way to go)
- Go语言学习之Arrays和Slices (The way to go)
- Go语言学习之运算符(The way to go)
- Go语言学习之method(The way to go)
- Go语言学习之errors包(The way to go)
- Go语言学习之Hello World(The way to go)
- Go语言学习之map (The way to go)
- Go语言学习之encoding/json包(The way to go)
- Go语言学习之new与make(The way to go)
- Go语言学习之变量(The way to go)
- Go语言学习之变量(The way to go)
- Go语言学习之struct(The way to go)
- Go语言学习之函数(The way to go)