The Iota Problem of Golang

Source: Internet
Author: User
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!!!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.