Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Objects and Generics

Variant Objects and Enums in Nim

Learn Nim enums, sets of enums and variant objects (case objects) that store different fields per case, plus how they map to tagged unions in memory.

Some data comes in a few fixed shapes: a token is a number or an operator or a name, a result is a value or an error. Nim models this with enums for the labels and variant objects (also called case objects) for data that differs per label. The compiler then makes sure you only touch the fields that exist.

The Nim code is read-only here; the C stand-ins show the tagged union that the compiler generates.

Enums and sets

An enum is an ordered list of named constants.

NIM
type
  Color = enum
    Red, Green, Blue

echo Green          # Green
echo ord(Blue)      # 2
echo Color(0)       # Red
for c in Color:     # iterate every value
  echo c

Enums can carry custom strings (Red = "r") or explicit numbers (Low = 1). Nim enums are ordinal, so you can use succ, pred, ord, low and high on them. Small ordinal types can form a set, which is stored as a bit mask:

NIM
type Perm = enum Read, Write, Exec
var p: set[Perm] = {Read, Write}
p.incl Exec
echo Write in p      # true
echo p - {Read}      # {Write, Exec}
C C stand-in: a set of enums is a bit mask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Variant objects

A variant object has a discriminator field, and the fields after a case depend on its value.

NIM
type
  TokenKind = enum
    tkNumber, tkOp, tkName

  Token = object
    case kind: TokenKind
    of tkNumber: value: float
    of tkOp:     op: char
    of tkName:   name: string

let t = Token(kind: tkNumber, value: 3.5)
echo t.value          # fine
# echo t.op           # raises FieldDefect at run time

You choose the case when you construct the object. Reading a field of another case is a run-time FieldDefect (or a compile error when the compiler can see it). Processing a variant is naturally a case statement, and Nim checks that every kind is handled:

NIM
proc show(t: Token): string =
  case t.kind
  of tkNumber: $t.value
  of tkOp:     $t.op
  of tkName:   t.name

If you add a new kind and forget a branch, compilation fails, which is the main advantage over a loose bag of optional fields.

How it looks in memory

All cases share one block of memory, sized for the largest case, next to the tag. This is a tagged union.

C C stand-in: a tagged union

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C leaves it to you to keep the tag and the union in sync. Nim's discriminator check does it for you.

Common patterns

  • Option-like results: a variant with ok and err cases, or the standard library's Option[T] (see Generics).
  • Syntax trees: a recursive variant whose cases hold ref children, the shape used in the macro AST.
  • State machines: an enum for the state and a variant for the per-state data.
C C stand-in: enum-driven state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the field after case kind: decide?

    The discriminator selects which branch of fields the object has.
  2. 2. What happens when you read a field of the wrong case?

    Nim checks the discriminator and raises FieldDefect.
  3. 3. How is set[Perm] stored?

    Sets of small ordinal types are bit sets.
  4. 4. Why use a case statement over a variant?

    Exhaustiveness checking catches forgotten cases when you add a kind.

Summary

  • Enums are ordered named constants; set[Enum] is a bit mask.
  • Variant objects pick their fields by a discriminator.
  • Wrong-case access raises FieldDefect; case statements are checked for completeness.
  • In memory a variant is a tagged union.

Next: Generics and Concepts