Golang 如何使用iota
Go 中的 Iota 是用来表示常数增加的序列。当在一个常数中重复时,它的值在每次规范后都会被递增。在这篇文章中,我们将探讨在Go中使用 iota 的不同方式。
首先让我们考虑一个非常基本的例子,我们将声明多个常数并使用iota。
例子1
考虑一下下面的代码
package main
import (
"fmt"
)
const (
first = iota
second = iota
third = iota
)
func main() {
fmt.Println(first, second, third)
}
输出
如果我们运行命令 go run main.go ,那么我们将在终端得到以下输出。
0 1 2
我们也可以省略上述例子中 iota 关键字的重复。考虑一下下面的代码。
例2
package main
import (
"fmt"
)
const (
first = iota
second
third
)
func main() {
fmt.Println(first, second, third)
}
输出
如果我们运行命令 go run main.go ,那么我们将在终端得到以下输出。
0 1 2
没有必要用默认值来启动 iota ,我们也可以用1来启动它。
例3
考虑一下下面的代码
package main
import (
"fmt"
)
const (
first = iota + 1
second
third
)
func main() {
fmt.Println(first, second, third)
}
输出
如果我们运行命令 go run main.go ,那么我们将在终端得到以下输出。
1 2 3
我们也可以在使用 iota 时跳过这些值。
例4
考虑一下下面的代码。
package main
import (
"fmt"
)
const (
first = iota + 1
second
_
fourth
)
func main() {
fmt.Println(first, second, fourth)
}
输出
如果我们运行命令 go run main.go ,那么我们将在终端得到以下输出。
1 2 4