liveBook · Manning

Enum

As explained in Learn Go with Pocket-Sized Projects

An enumeration is a finite set of named values representing alternatives of the same conceptual kind.

A logger needs a small, defined set of levels: Debug for diagnostic detail, Info for meaningful events, and Error for failures. In Go, a named type and a group of constants give these alternatives readable names instead of passing around unexplained numbers. section 4.1.2

const (
   // LevelDebug represents the lowest level of log, mostly used for 
    // debugging purposes.
   LevelDebug Level = iota
   // LevelInfo represents a logging level that contains information 
    // deemed valuable.
   LevelInfo
   // LevelError represents the highest logging level, only to be used 
    // to trace errors.
   LevelError
)

The exported Level type uses byte as its underlying type. The constants use iota to assign successive values, and each exported name has a documentation comment. section 4.1.2

Use this pattern for a small, finite set of states or modes. A domain-specific type makes the API clearer than a bare integer; export its values when callers need to use them. section 4.6 section 4.1.2

Character feedback

A word game represents each character’s result as absent, misplaced, or correct. Its hint type uses byte and iota, with absent first so the zero value is useful. The numeric order runs from worst to best, which also helps when selecting the best hint. section 5.2.1

A hint can also implement String() string. A switch selects its display representation, allowing fmt printing to use that representation through the Stringer interface; a default case handles an unexpected value. section 5.2.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Works through named byte types, iota constants, zero-value ordering, and a Stringer method.
Examples
Uses three logger levels and three word-game character hints as concrete implementations.
What you can do after
Build it from scratch using a named Go type and iota constants, choosing an order that makes the zero value useful.
How it connects
Connects enums to exported APIs, domain-specific types, zero values, switch statements, and the Stringer interface.

Also explained in

Compare how 23 books explain enum →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.