3. Iota

Go has a language feature that, when used with a type definition (and if you squint really hard), kinda looks like an enum (but it's not). It's called iota.

type sendingChannel int

const (
    Email sendingChannel = iota
    SMS
    Phone
)

The iota keyword is a special keyword in Go that creates a sequence of numbers. It starts at 0 and increments by 1 for each constant in the const block. So in the example above, Email is 0, SMS is 1, and Phone is 2.

Go developers sometimes use iota to create a sequence of constants to represent a set of related values, much like you would with an enum in other languages. But remember, it's not an enum. It's just a sequence of numbers.

Assignment

Define an emailStatus type that uses iota syntax to represent the following states:

  • EmailBounced: 0

  • EmailInvalid: 1

  • EmailDelivered: 2

  • EmailOpened: 3

package main

type emailStatus int

const (
	EmailBounced = iota
	EmailInvalid
	EmailDelivered
	EmailOpened
)
1

What is a Type?

A type tells Go what kind of data something is.

Examples:

Here:

  • int is a type

  • string is a type

  • bool is a type

Now look at this:

This creates a new custom type.

It is based on int, but it is NOT just an int.

This is important.

It means:

x is its own type. You cannot accidentally assign random integers to it without intention.

This gives your program more safety and clarity.

2

What is a Constant?

A constant is a value that never changes.

Example:

You cannot reassign it.

Now look at this:

This creates named constant values.

Instead of using random numbers like:

You use:

Much clearer.

3

What is iota Actually Doing?

iota is just a counter that resets inside each const block.

This:

Is the same as writing:

That’s it.

It just auto-increments.

Why Use This Instead of Just Numbers?

Because this is bad:

But this is clear:

Now your code explains itself.

Now Your Assignment

You want:

  • EmailBounced: 0

  • EmailInvalid: 1

  • EmailDelivered: 2

  • EmailOpened: 3

So the correct answer is: