There is a very unique thing in the Go language, and that is the iota constant. According to some incomplete statistics, many Go developers have transitioned from PHP, Java, C, Python, etc., and I am quite curious about this.
Let’s learn in depth with everyone today.
In Go, enumeration constants are created using the iota enumerator. Functionally, the iota keyword represents an integer constant starting from 0; In function, it can simplify the definition of constants using automatically incrementing numbers, which is very convenient.
Previously defined an enumeration value:
const ( a = 0 b = 1 c = 2 )
After Go has the iota keyword:
const ( a = iota b c )
The corresponding value result:
a=0 b=1 c=2
is even OK Jumping:
const ( a = iota _ b c )
The corresponding value result:
a=0 b=2 c=3
You can also play with flowers:
const ( bit0, mask0 = 1 << iota, 1<<iota - 1 bit1, mask1 _, _ bit3, mask3 )
The corresponding value result:
bit0 == 1, mask0 == 0 (iota == 0) bit1 == 2, mask1 == 1 (iota == 1) (iota == 2, unused) bit3 == 8, mask3 == 7 (iota == 3)
After having a certain basic understanding of iota, we started to enter our theme and spread our curiosity with fried fish.
In fact, iota is the full name, ask a question in stackoverflow [1] has been discussed by many community friends (as expected, there are quite a few curious friends).
Essentially "iota" is the 9th letter of the Greek alphabet. It is a typical mathematical symbol that represents something very small.
is often used in the following scenarios:
除了 Go 以外,在 APL、C++,又或是 Scheme 均有有 iota 常量的存在(设计),可以给到大家使用。
Scheme iota 的签名如下:
iota count [start step]
作用是返回一个包含计数数字的列表,从起始点开始,每次增加步长。默认的开始是0,默认的步骤是 1。
例如:
(iota 6) ⇒ (0 1 2 3 4 5) (iota 4 2.5 -2) ⇒ (2.5 0.5 -1.5 -3.5)
其实 iota 已经是迭代器的一个约定式命名了,可以认为是也业内通识。
在《The Go Programming Language Specification[2]》中存在着对 iota 的明确定义和说明。
如下:
在一个常量声明中,预先声明的标识符 iota 代表连续的无类型的整数常量。它的值是该常量声明中各 ConstSpec 的索引,从0开始。
提取核心意义:Go 中的 iota 是 ConstSpec 索引,也就是填补的是连续的无类型整数常量的位置。
因此 Go 中有它的一席位置。
在这篇文章中,我们介绍了 Go 中 iota 的基本语法。同时基于历史资料针对 iota 到底是什么,为什么要这么叫,又有什么用进行了一番研究。
也需要思考另外一个问题,并不是每一门语言都有 iota。那没有 iota 的话会怎么样,不存在是否也有其合理性呢?
The above is the detailed content of Why did Go design the iota constant?. For more information, please follow other related articles on the PHP Chinese website!