This is a creation in Article, where the information may have evolved or changed.
Often people think that iota is 0, but that is not the case.
To be exact, when Iota appears in the first line following the keyword const, the iota is 0, when the second row appears, the Iota is 1, and so on, and when Iota encounters the const again, it resets to 0.
Description of Golang spec about Iota: Http://golang.org/ref/spec#Iota
Let's look at a few pieces of code.
1, Example 1
Package Mainimport "FMT" Const I1 = iotaconst J1 = iotaconst K1 = Iotafunc Main () {FMT. Println ("I1, J1, K1", I1, J1, K1) fmt. Println ("Hello, Playground")}
Http://play.golang.org/p/LQEyApa6dq
Output:
I1, J1, K1 0 0 0
2, Example 2
Package Mainimport "FMT" const (i1 = IOTAJ1 = Iotak1 = Iota) func main () {FMT. Println ("I1, J1, K1", I1, J1, K1) fmt. Println ("Hello, Playground")}
Output:
I1, J1, K1 0 1 2
Http://play.golang.org/p/gVhf2oC3Y4
This is the example we use most often.
3, Example 3
Package Mainimport "FMT" const (i1, J1,k1 = iota, iota, Iota) func main () {FMT. Println ("I1, J1, K1", I1, J1, K1) fmt. Println ("Hello, Playground")}
Http://play.golang.org/p/W1-umpoOwS
Output:
I1, J1, K1 0 0 0
In this example, because Iota is on the same line, it is calculated only once, which is 0
4, Example 4
Package Mainimport "FMT" const (i1 = -1J1 = Iotak1) func main () {FMT. Println ("I1, J1, K1", I1, J1, K1) fmt. Println ("Hello, Playground")}
Http://play.golang.org/p/C8ff8k1JAS
Output:
I1, J1, k1-1 1 2
In this example, because Iota appears in the second line of the const, it is 1, which is the most common mistake!!!