0Pricing
Zig Academy · Lesson

Tagged Unions and switch

Pattern-match over union variants.

Remembering the Variant

A plain union forgets which field is active. A tagged union pairs the value with an enum tag that records the current variant.

Declaring a Tagged Union

You write union(enum) to let Zig generate a matching tag automatically, one tag name per field.

const Value = union(enum) { int: i64, text: []const u8 };

All lessons in this course

  1. Enums for a Fixed Set of Values
  2. Unions That Hold One of Many Types
  3. Tagged Unions and switch
  4. Enum Methods and Backing Integers
← Back to Zig Academy