主要讲解Go语言中常量和枚举定义和使用
主要知识点:
- Go语言中定义常量,名称不使用大写
- 定义常量的两种方式,单个定义和集中定义
- 枚举的几种定义方式
- 使用 iota 关键字 实现 枚举值的 设置
以下为代码示例:
package main
import "fmt"
//Go 中的常量名称不用大写,在Go中大写变量名有其它含义
//定义一组常量
const(
a1="aa"
b2=1.26
)
//在函数中单个定义常量
func consts(){
const filename ="abc"
const a,b=1,false
fmt.Println(filename,a,b,a1,b2) //abc 1 false aa 1.26
}
//Go中没有专门为枚举定义关键字,但是可以借助常量来实现
// 1、 枚举普通实现
func emums1(){
const(
cpp = 0
java = 1
python = 2
golang = 3
javascript = 4
)
fmt.Println(python,javascript) //2 4
}
//2、枚举简化实现
// Go 提供了 iota 关键字 代表一组 常量自增,可以使用 _ 跳过自增值
func emums2(){
const(
cpp = iota
_
python
golang
javascript
)
fmt.Println(cpp,golang) //0 3
}
//3、iota 深入用法,枚举值可以使用 iota 参与表达式 进行计算
func emums3(){
const(
cpp = (iota*10)+1
_
python
golang
javascript
)
fmt.Println(cpp,golang) //1 31
}
func main() {
consts()
emums1()
emums2()
emums3()
}