Skip to the workspace
Pebellslearn by building
Types and Error Handling  ›  Lesson

Enums: One of Several Shapes

Enums 12 minAn enum defines a type that is exactly one of several named variants, each able to carry its own data, and match handles every variant.

rust / Enums: One of Several Shapes

Explore each scene at your own pace.

01 · The rule

The rule

Enums: One of Several Shapes

An enum defines a type that is exactly one of several named variants, each able to carry its own data, and match handles every variant.

Represent alternatives with their own associated data and inspect each variant.

A book in the library is on the shelf, or out on loan, or lost. Never two at once. A struct full of true/false flags can describe impossible mixtures; an enum cannot. Enums are also how Rust represents "a value or nothing" and "success or failure", which is why they belong in this section on errors.

The rule

An enum is exactly one variant at a time, and each variant carries its own data.

enum Status {
    OnShelf,
    OnLoan { card: u32, due_day: u32 },
    Lost,
}

let s = Status::OnLoan { card: 1042, due_day: 21 };
  • Variants are named with Type::Variant.
  • A variant can hold nothing (OnShelf), named fields (OnLoan { ... }), or unnamed ones like Damaged(String).
  • The data belongs to its variant: a book on the shelf simply has no card number.

Handle an enum with match, which must cover every variant and can pull out the data:

fn describe(s: &Status) -> String {
    match s {
        Status::OnShelf => String::from("available"),
        Status::OnLoan { card, due_day } => format!("with card {card} until day {due_day}"),
        Status::Lost => String::from("lost"),
    }
}

Enums get impl blocks just like structs, so describe could be a method, s.describe().

When you later add a variant, say Repair, every match without a catch-all stops compiling until you handle it. That is a feature: the compiler lists every place to update.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.