Thursday, April 25, 2024
HomeGolangiota in Go (Golang) - tips on how to use?

iota in Go (Golang) – tips on how to use?



The iota key phrase inside a fixed declaration represents successive untyped integers ranging from zero. When declaring constants, it usually doesn’t matter what their particular values are, however that they’re distinct from one another, so as a substitute of declaring constants within the kind:

const (
	Strawberry = "strawberry"
	Blueberry  = "blueberry"
	Raspberry  = "raspberry"
)

we are able to declare them as integers:

const (
	Strawberry = 1
	Blueberry  = 2
	Raspberry  = 3
)

and this declaration may be additional simplified by the iota key phrase:

const (
	Strawberry = iota + 1
	Blueberry // in Go, omitting the worth of fixed 
        // throughout the constants listing declaration is equal 
        // to repeating the earlier line worth
	Raspberry
)

The iota key phrase begins a counter that increments for every line of the const declaration. As a result of its preliminary worth is zero, within the instance above, we declare the primary fixed as iota + 1. In consequence, we obtain 1 for Strawberry, 2 for Blueberry, and 3 for Raspberry.

Skip iota worth

If you wish to skip an integer worth in const declaration with iota, you should utilize the clean identifier _:

bundle important

import "fmt"

const (
	Strawberry = iota + 1
	Blueberry
	Raspberry
	_
	Apple
)

func important() {
	fmt.Println(Strawberry, Blueberry, Raspberry, Apple)
}

Superior instance

Along with merely incrementing values, the iota key phrase can be used to compute extra complicated expressions. The instance beneath, from Efficient Go, reveals the mix of the iota key phrase, bitwise shift, and a customized kind declaration with a String() methodology that codecs the information in a different way relying on the worth.

bundle important

import "fmt"

kind ByteSize float64

const (
	KB ByteSize = 1 << (10 * (iota + 1))
	MB
	GB
)

func (b ByteSize) String() string {
	swap {
	case b >= GB:
		return fmt.Sprintf("%.2fGB", b/GB)
	case b >= MB:
		return fmt.Sprintf("%.2fMB", b/MB)
	case b >= KB:
		return fmt.Sprintf("%.2fKB", b/KB)
	}
	return fmt.Sprintf("%.2fB", b)
}

func important() {
	fmt.Println(1001*KB, 2.5*MB, 3.5*GB)
	fmt.Println(ByteSize(121000000))
}

Output:

1001.00KB 2.50MB 3.50GB
115.39MB
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments