27

关于Golang中的iota

 3 years ago
source link: https://studygolang.com/articles/30042
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

快速一览

iota是Golang中提供的一个简化常量和枚举编程的标识符,合理的使用这个标识符可以让代码变得更简洁,省去大量的不必要的代码。

比如下面的这个常量定义

const (
    a = 1
    b = 2
    c = 3
)

使用iota可以写成如下的方式

const (
  a = iota + 1
  b
  c
)

剖析

iota的用法很灵活,但是只要掌握了它的基本规则,就可以很熟练地使用它

  • iota是一个从 0 开始递增的整形值
  • iota可以用在 const 定义块的任何位置,并且它的当前值取决于它所在的位置
    const (
      a = 4    // 显式的指定值
      b = 5    // 显式的指定值
      c = iota // c = 2,因为这里的 iota 位于第3个ConstSpec,2=3-1
      d        // d = 3,因为iota递增了1,等价于 d = iota
    )
  • iota可以使用在一个表达式里面,并且在它之后的常量(如果没有显示地指定值)都按照这个表达式,在iota递增的基础上进行赋值
    const (
      a = iota * 2 // a = 0
      b            // b = 2
      c            // c = 4
      d            // d = 6
    )

扩展

有了上面的三个规则,我们可以列举一些非常规但是合法的方式,你会发现,这些方式都离不开以上的规则。

跳过iota递增的某些值

const (
    a = iota               // a = 0
    _                      // 跳过这个ConstSpc,但是iota会加1
    b, c = iota, iota * 2  // iota=2
  )
// a=0, b=2, c=4

使用分号,在一行指定多个ConstSpec

const (
    a = iota               // a = 0
    b = iota; c = iota     // b = 1, c = 2
  )

在上面的例子中,虽然 bc 在同一行上,但是他们是两个不同的ConstSpec,所以iota也是不一样的。

有疑问加站长微信联系

iiUfA3j.png!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK