站长资讯网
最全最丰富的资讯网站

golang iota从几开始

golang iota从几开始

iota是golang语言的常量计数器,只能在常量的表达式中使用。

iota在const关键字出现时将被重置为0(const内部的第一行之前),const中每新增一行常量声明将使iota计数一次(iota可理解为const语句块中的行索引)。 (推荐学习:go)

使用iota能简化定义,在定义枚举时很有用。

在常量定义中,iota可以方便的迭代一个值从0以步长1递增,0,1,2,3,4,5…

本例以文件大小的格式2的10次方进位一次为依据,将KB为1左移10位,MB左移20位。。。

本文中的Sprintf(“%f”,x)并不会因为定义在String方法内而引起无穷循环bug,因为%f不会去尝试调用String()

package main import (     "fmt" ) type ByteSize float64 const (     _ = iota     KB ByteSize = 1 << (10*iota)     MB     GB     TB     PB     EB     ZB     YB ) func (b ByteSize) String() string{     switch {         case b >= YB:             return fmt.Sprintf("%.2fYB",b/YB)         case b >= ZB:             return fmt.Sprintf("%.2fZB",b/ZB)         case b >= EB:             return fmt.Sprintf("%.2fEB",b/EB)         case b >= PB:             return fmt.Sprintf("%.2fPB",b/PB)         case b >= TB:             return fmt.Sprintf("%.2fTB",b/TB)         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(ByteSize(1e10)) }

赞(0)
分享到: 更多 (0)

网站地图   沪ICP备18035694号-2    沪公网安备31011702889846号