SoFunction
Updated on 2025-03-05

Iota keywords in Go language

1. Review constants

When it comes to the keyword Iota, you must review the constants of Go language.

Language constants are generally declared using const

Language constants can only be Boolean, numeric (integer, floating point, and complex) and string

The language constants can be specified without specifying a type and are inferred by the compiler themselves. For example, the following [string] can be written without writing (also known as implicit type definition)

const s string = "constant"

4. Constants cannot be changed when the program is running

2. How to use Iota

From a specific example, let’s look at the characteristics of iota. What is the value of each constant output result in the code below?

package IotaDemo

import (
    "fmt"
)

const(
    a = iota
    b
    c
)

const(
    m=1<<iota
    n=2<<iota
    x=10
    y = iota
    z=iota>>1
    o
)

func IotaTest() {

    ("a=",a)
    ("b=",b)
    ("c=",c)

    ("m=",m)
    ("n=",n)
    ("x=",x)
    ("y=",y)
    ("z=",z)
    ("o=",o)
}

The results are as follows:

a= 0
b= 1
c= 2
m= 1
n= 4
x= 10
y= 3
z= 2
o= 2

The above results illustrate the characteristics of iota, as follows:

  • iota can only be used in const limitation, equivalent to a constant counter
  • iota is equivalent to an enum value, which starts from 0 by default. In a const, +1 will be performed, such as a, b, and c, which can be seen.
  • iota will not increase because a fixed value is assigned in const. Every constant in const will +1. For example, x and y are not assigned to 10 because x is assigned to 10, which is 2, but 3.
  • Every time you enter a new const, iota will start the calculation again

Supplementary shift operation knowledge points:

For the << (right) and >> (left) operations of Go language, the key points are as follows:

  • 1. Convert the shifted value into 2-digit first. Move right to make up for 0 at the high position, and shift left to make up for 0 at the low position
  • 2. The operator on the right side is the number of bits to be moved, and the left side is the value to be moved.

For example, 1<<3 is to move 1 to the left by 3 bits, that is, 00000001 shift 3 bits to the left and becomes 00000100, which is 4

3<<1 means to move 3 to the left by 1, that is, 00000011, and move 1 to the left by 00000110 means 6

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the following links