Enums in Go - Iota



 Yes, you read it right.

Like many other languages Go support the concept of enums through the IOTA function.

IOTA

According to Go documentation 

Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants. Its value is the index of the respective ConstSpec in that constant declaration, starting at zero. It can be used to construct a set of related constants. 

Don't worry if you didn't get it.

Basically, Iota is a keyword in Go that helps you to give random values to your constant.

Let's say you want to define 7 constant Monday, Tuesday, Wednesday .... Sunday.

Easy way to do this is

const (
Monday = 1
Tuesday = 2
Wednesday = 3
Thursday = 4
Friday = 5
Saturday = 6
)


In this situation, values 1,2,3,4,5,6 don't make much sense. The only thing these values should follow is that they have to be unique i.e Monday should not be equal to any other value.

These are just 7 unique values, if you were to create let's say 100 such values you don't have to assign unique values to these constants, you can use iota to get unique values for all these constants.

const (
Monday = iota
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
)

This will automatically assign unique values to all these constant variables.

By default, it starts the values from 0 and increments the values by 1 with every constant but this is not something we can rely on, so be careful while using Iota.


Thanks for reading this microblog.

Happy Learning

- The Data Singh



Comments

Post a Comment

Popular posts from this blog

Spidering the web with Python

Word Vectorization

Machine Learning -Solution or Problem