美文网首页
常量及iota的简单用法

常量及iota的简单用法

作者: YXWKY | 来源:发表于2020-10-23 15:15 被阅读0次

一,常量

  • 介绍
    常量是在编译时期创建的,即使当定义在函数内,并且只能是numbers,characters(runes),strings或者booleans。由于编译时的限制,定义它们的表达式必须是可由编译器求值的常量表达式。
  • 常量表达式案例
    1 << 4是一个常量表达式。
    math.Sin(math.Pi/3)不是常量表达式,因为math.Sin是在运行时执行的。

二,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)
}
  • iota每遇到一个const都会清零

  • 默认是从0开始,所以上面的( - = iota )表示抛弃第一个为0的数据

  • const 集合中从上到下,iota是逐步递增的,案例 1 << (10 * iota) 中的iota值为1,所以实际上是1左移10位等于1024,MB则是左移20位。依次类推知道YB。

  • 民间案例

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

相关文章

  • 常量及iota的简单用法

    一,常量 介绍常量是在编译时期创建的,即使当定义在函数内,并且只能是numbers,characters(rune...

  • Go语言--iota枚举

    介绍 iota 常量自动生成器,每个一行,自动累加1 iota给常量赋值使用3.iota遇到const,重置为04...

  • go IOTA常量计数器1期

    iota是golang语言的常量计数器,只能在常量的表达式中使用。 iota在const关键字出现时将被重置为0(...

  • A Note of Effective Go (Second H

    Initialization Constants用iota创建枚举常量 Variables The init fu...

  • golang学习笔记--iota

    go中的iota 1.iota只能在常量的表达式中使用、2.每次const出现时都会让iota初始化为03.用作枚...

  • Golang 常量使用iota

    基本概念 iota是Go语言的常量计数器,只能在常量的表达式中使用。iota默认值为0,在且仅在const关键字出...

  • 04 | 常量与iota

    常量 使用const定义,类型可不指定 常量可以是字符、字符串、布尔值或数值(整数型、浮点型和复数) 常量的值必须...

  • 《Go语言四十二章经》第四章 常量

    《Go语言四十二章经》第四章 常量 作者:李骁 4.1 常量以及iota 常量使用关键字 const 定义,用于存...

  • golang 常量的iota使用

    在常量定义中,iota可以方便的迭代一个值从0以步长1递增,0,1,2,3,4,5...本例以文件大小的格式2的1...

  • 第01天(基本类型、流程控制)_02

    07_常量的使用.go 08_多个变量或常量定义.go 09_iota枚举.go 10_bool类型.go 11_...

网友评论

      本文标题:常量及iota的简单用法

      本文链接:https://www.haomeiwen.com/subject/mebsvctx.html