常量及iota的简单用法

2020-10-23  本文已影响0人  YXWKY

一,常量

二,iota的使用注意事项

官方介绍:在Go中,枚举常量的创建推荐使用iota,由于iota能够作为表达式的一部分且能够隐式的重复,因此很容易的去构建复杂的值集。

type ByteSize float64

const (
    _           = iota // ignore first value by assigning to blank identifier
    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)
}
const (
            a = iota   //0
            b          //1
            c          //2
            d = "ha"   //独立值,iota += 1
            e          //"ha"   iota += 1
            f = 100    //iota +=1
            g          //100  iota +=1
            h = iota   //7,恢复计数
            i          //8
    )

结果:

0 1 2 ha ha 100 100 7 8

通过该案例可以明显看到iota遇到主动赋值的条目时,并不会终止累加,而是会继续隐式增加iota的值。

参考:
https://golang.google.cn/doc/effective_go.html#initialization
https://blog.csdn.net/cbwcole/article/details/102868825

上一篇 下一篇

猜你喜欢

热点阅读