Go: Working with iota

Filipe Munhoz
2 min readAug 16, 2020

--

The iota's keyword in golang is used to autoincrement a int or float variable inside de Const clause. It also can be used to declare an enum.

Declaring a iota

In this example you can see the behavior when assigning iota in an untyped variable "a" and a typed variable "b" and "c".

package mainimport "fmt"const (
a = iota
b int = iota
c float64 = iota
)
func main() { fmt.Printf("%v — %T\n", a, a)
fmt.Printf("%v — %T\n", b, b)
fmt.Printf("%v — %T\n", c, c)
}

Result

0 — int
1 — int
2 — float64

Ignoring first generated value

It's possible to ignore the first generated value using iota, all you need to do, is assign iota to a underscore "_" and next const element will be assigned to 1. See the example:

package mainimport "fmt"const (
_ = iota
a = iota
b int = iota
c float64 = iota
)
func main() {
fmt.Printf("%v — %T\n", a, a)
fmt.Printf("%v — %T\n", b, b)
fmt.Printf("%v — %T\n", c, c)
}

Result

1 — int
2 — int
3 — float64

Operations with iota

It's possible to make operation when using iotas

package mainimport "fmt"const (
_ = iota
a = iota + 10
b int = iota * 10
c float64 = iota + 5.1
)
func main() {
fmt.Printf("%v — %T\n", a, a)
fmt.Printf("%v — %T\n", b, b)
fmt.Printf("%v — %T\n", c, c)
}

Result

11 — int
20 — int
8.1 — float64

Reseting iota increment

Everytime a keywork Const appears in the code, iota's increment is reseted

package mainimport "fmt"const (
a = iota
b int = iota
)
const (
c = iota
)
func main() {
fmt.Printf("%v — %T\n", a, a)
fmt.Printf("%v — %T\n", b, b)
fmt.Printf("%v — %T\n", c, c)
}

Result

0 — int
1 — int
0 — int

Declaring enum with iota

Another good way to use iota is to declare a enum

package mainimport "fmt"// Size int — using enum type
type Size int
// Const for enum
const (
Small Size = iota
Medium
Big
Huge
)
func main() {
var s Size = Medium
fmt.Println("Size: ", s)
}
func (d Size) String() string {
return […]string{"Small", "Medium", "Big", "Huge"}[d]
}

Result

Size: Medium

Full Source Code

Thanks for reading.

--

--

Filipe Munhoz
Filipe Munhoz

Written by Filipe Munhoz

Software Engineer at Itaú Unibanco

No responses yet