Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How to use iota in Golang?
Iota in Go is used to represent constant increasing sequences. When repeated in a constant, its value gets incremented after each specification. In this article, we will explore the different ways in which we can use iota in Go.
Let's first consider a very basic example, where we will declare multiple constants and use iota.
Example 1
Consider the code shown below
package main
import (
"fmt"
)
const (
first = iota
second = iota
third = iota
)
func main() {
fmt.Println(first, second, third)
}
Output
If we run the command go run main.go, then we will get the following output in the terminal.
0 1 2
We can also omit the repetition of the iota keyword in the above example. Consider the code shown below.
Example 2
package main
import (
"fmt"
)
const (
first = iota
second
third
)
func main() {
fmt.Println(first, second, third)
}
Output
If we run the command go run main.go, then we will get the following output in the terminal.
0 1 2
It is not necessary to start the iota with the default value; we can start it with 1 also.
Example 3
Consider the code shown below
package main
import (
"fmt"
)
const (
first = iota + 1
second
third
)
func main() {
fmt.Println(first, second, third)
}
Output
If we run the command go run main.go, then we will get the following output in the terminal.
1 2 3
We can also skip the values while using iota.
Example 4
Consider the code shown below.
package main
import (
"fmt"
)
const (
first = iota + 1
second
_
fourth
)
func main() {
fmt.Println(first, second, fourth)
}
Output
If we run the command go run main.go, then we will get the following output in the terminal.
1 2 4
