Wednesday, 1 May 2019

Go language: iota identifier


‘iota’ identifier is used in const declarations to simplify definitions of incrementing numbers.

Example

const (
         first = iota
         second
         third
         fourth
)

‘iota’ starts with number 0 and assign subsequent constants by incrementing the variable value by 1.

HelloWorld.go
package main

import "fmt"

const (
 first = iota
 second
 third
 fourth
)

func main() {

 fmt.Println("first : ", first)
 fmt.Println("second : ", second)
 fmt.Println("third : ", third)
 fmt.Println("fourth : ", fourth)

}

Output
first :  0
second :  1
third :  2
fourth :  3

Each ‘const’ block has its own iota.

const (
         block1First = iota
         block1Second
)

const (
         block2First = iota
         block2Second
         block2Third
)


HelloWorld.go
package main

import "fmt"

const (
 block1First = iota
 block1Second
)

const (
 block2First = iota
 block2Second
 block2Third
)

func main() {

 fmt.Println("block1First : ", block1First)
 fmt.Println("block1Second : ", block1Second)
 fmt.Println("block2First : ", block2First)
 fmt.Println("block2Second : ", block2Second)
 fmt.Println("block2Third : ", block2Third)

}

Output
block1First :  0
block1Second :  1
block2First :  0
block2Second :  1
block2Third :  2

Using iota in constant expressions
We can use iota in constant expressions.

const (
         first = 1 << iota
         second
         third
         fourth
         five
         six
)

Value of
first is 1 << 0
second is 1 << 1
third is 1 << 2
fourth is 1 << 3 etc,


HelloWorld.go
package main

import "fmt"

var a int = 10

const (
 first = 1 << iota
 second
 third
 fourth
 five
 six
)

func main() {

 fmt.Println("first : ", first)
 fmt.Println("second : ", second)
 fmt.Println("third : ", third)
 fmt.Println("fourth : ", fourth)
 fmt.Println("five : ", five)
 fmt.Println("six : ", six)

}

Output
first :  1
second :  2
third :  4
fourth :  8
five :  16
six :  32



Previous                                                 Next                                                 Home

No comments:

Post a Comment