Go中的iota - 如何使用?(附实例)

85 阅读1分钟

常数声明中的 iota关键字在常量声明中代表从零开始的连续的未定型整数。在声明常量时,它们的具体数值往往并不重要,重要的是它们彼此之间是不同的,所以不要以.的形式声明常量。

const (
Strawberry = "strawberry"
Blueberry = "blueberry"
Raspberry = "raspberry"
)

我们可以将它们声明为整数

const (
Strawberry = 1
Blueberry = 2
Raspberry = 3
)

的形式来声明常量,这种声明可以通过以下方式进一步简化 iota关键字来进一步简化:

const (
Strawberry = iota + 1
Blueberry // in Go, omitting the value of constant
 // within the constants list declaration is equivalent
 // to repeating the previous line value
 Raspberry
)

这个 iota关键字启动了一个计数器,在const 声明的每一行中都会递增。因为它的初始值是零,在上面的例子中,我们将第一个常量声明为 iota + 1.结果是,我们收到1 ,用于Strawberry2 ,用于Blueberry3 ,用于Raspberry

跳过 iota

如果你想在const 声明中跳过一个整数值,用 iota,你可以使用空白标识符_ :

package main
import "fmt"
const (
Strawberry = iota + 1
Blueberry
Raspberry
_
Apple
)
func main() {
fmt.Println(Strawberry, Blueberry, Raspberry, Apple)
}

高级示例

除了简单的增量值之外,该 iota关键字还可以用来计算更复杂的表达式。下面的例子来自Effective Go,显示了 iota关键字、位数移位和自定义类型声明的结合。 String()方法,该方法根据值的不同而对数据进行不同的格式化。

package main
import "fmt"
type ByteSize float64
const (
KB ByteSize = 1 << (10 * (iota + 1))
MB
GB
)
func (b ByteSize) String() string {
switch {
case b >= GB:
return fmt.Sprintf("%.2fGB", b/GB)
case b >= MB:
return fmt.Sprintf("%.2fMB", b/MB)
case b >= KB:
return fmt.Sprintf("%.2fKB", b/KB)
}
return fmt.Sprintf("%.2fB", b)
}
func main() {
fmt.Println(1001*KB, 2.5*MB, 3.5*GB)
fmt.Println(ByteSize(121000000))
}

输出

1001.00KB 2.50MB 3.50GB
115.39MB