Ad space (banner)
๐ŸนGo Lessons
Lesson 41 / 68

Enum Basics (iota)

In this lesson you will learn to build an enum with iota in Go, so a fixed set of options can be referred to by readable names. This is for anyone searching for "Go iota how to use".

Go has no dedicated enum syntax, but iota lets you declare a run of sequential constants together, reproducing an enumerated type. Use it when you want to limit the possible values in advance, the way a traffic light only has red, green, and amber.

The sample code declares sequential constants with const (Red Color = iota; Green; Blue) and implements a func (c Color) String() string method so they display as names such as "Red" rather than as numbers.

A common stumbling block for beginners is that iota is, underneath, simply generating sequential integers. Even so, a named constant conveys intent better than a bare number and guards against typos.

In real-world development, being able to work with named constants while keeping type safety is exactly the advantage of this iota-based approach.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)