= 1e20 // float64 to int, overflows
)
枚举
关键字 iota 定义常量组中从 0 开始按?行计数的?自增枚举值。
const (
Sunday = iota // 0
Monday // 1,通常省略后续?行表达式。
Tuesday // 2
Wednesday // 3
Thursday // 4
Friday // 5
Saturday // 6
)
const (
_ = iota // iota = 0
KB int64 = 1 << (10 * iota) // iota = 1
MB // 与 KB 表达式相同,但 iota = 2
GB
TB
)
在同?一常量组中,可以提供多个 iota,它们各?自增?长。
const (
A, B = iota, iota << 10 // 0, 0 << 10
C, D // 1, 1 << 10
)
如果 iota ?自增被打断,须显式恢复。
const (
A = iota // 0
B // 1
C = "c" // c
D // c,与上?一?行相同。
E = iota // 4,显式恢复。注意计数包含了 C、D 两?行。
F // 5
)
可通过?自定义类型来实现枚举类型限制。
type Color int
const (
Black Color = iota
Red
Blue
)
func test(c Color) {}
func main() {
c := Black
test(c)
x := 1
test(x) // Error: cannot use x (type int) as type Color in function argument
test(1) // 常量会被编译器?自动转换。
}
在go语言中,没有直接支持枚举的关键字,也就造成go没有直接枚举的功能。但是go提供另一种方法来实现枚举,那就是const+iota
package main
import(
"fmt"
)
type State int
const (
Running State = iota
Stopped
Rebooting
Terminated
)
func (this State) String()string{
switch this {
case Running :
return "Running"
case Stopped :
return "Stopped"
default :
return "Unknow"
}
}
func main(){
state := Stopped
fmt.Println("state", state)
}
运行...
state Stopped