Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 132 ยท Structs, Enums and Traits Basics

Enums

Learn Rust enums - variants that carry data, Option and Result as enums, impl on enums, C-like enums with discriminants, enum size and state machines.

A struct says "a value has this and this and this". An enum says "a value is this or that or that". A traffic light is red, yellow or green. A network message is a connect request, a chat line or a goodbye. Whenever a value can be exactly one of several alternatives, an enum is the right tool, and Rust's enums are far more powerful than the ones in C or Java: each alternative (called a variant) can carry its own data.

This lesson shows how to define enums, attach data to variants, use match to take them apart, meet Option and Result as ordinary enums, give enums methods, work with C-like enums and their numeric values, understand enum size, and model a small state machine. The follow-up, Modelling with Enums and Pattern Matching, applies all of this to larger designs.

Defining a simple enum

List the variants inside braces. Variants live in the enum's namespace, so you write Direction::North:

Rust A simple enum and match

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 io::stdin().read_line()), it gets the next line from this box.

A value of type Direction is always one of the four variants; there is no null and no invalid fifth state. The match must cover every variant. If you forget one, the program does not compile:

Rust A non-exhaustive match (fails on purpose)

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 io::stdin().read_line()), it gets the next line from this box.

The compiler reports:

TEXT
error[E0004]: non-exhaustive patterns: `Light::Yellow` not covered
  --> main.rs:8:11
   |
 8 |     match l {
   |           ^ pattern `Light::Yellow` not covered
   |
note: `Light` defined here
  --> main.rs:1:6
   |
 1 | enum Light {
   |      ^^^^^
 2 |     Red,
 3 |     Yellow,
   |     ------ not covered
   = note: the matched value is of type `Light`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
   |
10 ~         Light::Red => false,
11 ~         Light::Yellow => todo!(),
   |

The message names the missing variant and suggests adding an arm. This exhaustiveness check is one of Rust's best features: when you add a variant to an enum later, the compiler points at every match that needs updating.

You can shorten the paths with use: use Direction::*; or use Direction::{North, South}; brings variants into scope. Use it in small, local scopes only, because a glob import hides where names come from.

Variants that carry data

Each variant may hold values, in the same three shapes that structs have: tuple-like, struct-like or none.

Rust Variants with data

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 io::stdin().read_line()), it gets the next line from this box.

In the match arms, the pattern binds the data to names (r, width, height, ...), which you can use in the arm. The data exists only in the matching variant, so you cannot accidentally read the radius of a rectangle. This is the key difference from "a struct with an optional field for everything": the type itself guarantees which fields exist.

Because all variants live in one type, you can store different shapes in one Vec<Shape> without any pointers or inheritance. Compare this with Trait Objects, which solve a similar problem when the set of alternatives is open-ended.

Option and Result are enums

Two enums from the standard library are used everywhere. They are defined like this (simplified):

Rust
enum Option<T> {
    None,
    Some(T),
}

enum Result<T, E> {
    Ok(T),
    Err(E),
}

There is no magic. "No value" is a normal variant, which the compiler forces you to handle, and that is how Rust avoids null-pointer bugs. You learned about them in Option and Handling Absence; see how they behave when matched by hand:

Rust Option and Result are just enums

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 io::stdin().read_line()), it gets the next line from this box.

When you only care about one variant

A full match is noisy when only one variant matters. if let handles one case, and let ... else extracts the value or leaves the function early. Both are refutable patterns: they may fail to match, and you decide what happens then.

Rust if let, let-else and match guards

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 io::stdin().read_line()), it gets the next line from this box.

The if w > h after a pattern is a guard: the arm applies only if the pattern matches and the condition holds. Note that the compiler cannot reason about guards when checking exhaustiveness, so a match that relies on guards still needs a final unguarded arm.

Methods on enums

Enums get impl blocks just like structs (Methods and Associated Functions). Inside, match self is the usual pattern, and a method taking &self reads the enum in place:

Rust impl on an enum

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 io::stdin().read_line()), it gets the next line from this box.

#[derive(Clone, Copy)] makes these tiny fieldless enums behave like integers (they are copied, not moved), so self by value is cheap. matches! is a macro that returns whether a value fits a pattern; Patterns in Depth covers it. Equality (==) between enum values needs #[derive(PartialEq)].

C-like enums and discriminants

An enum without data in any variant is called C-like. Each variant has a hidden integer, the discriminant, starting at 0 by default. You can set it explicitly and read it with an as cast:

Rust Discriminants and as casts

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 io::stdin().read_line()), it gets the next line from this box.

Casting from an enum to an integer is easy. The other direction is deliberately not allowed, because an arbitrary number may not correspond to a variant. Write a TryFrom<u8> implementation or a match that returns an Option (see Display, From and Standard Conversion Traits):

Rust Converting a number back to an enum

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 io::stdin().read_line()), it gets the next line from this box.

Only enums without data can be cast with as. An enum with data-carrying variants has no single integer to cast to; to inspect which variant you have, use match, if let or matches!.

Enum size and memory

An enum value stores a tag (which variant is it) plus enough room for the largest variant's data. So an enum is as big as its biggest variant plus the tag, rounded for alignment:

Rust Enum size follows the biggest variant

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 io::stdin().read_line()), it gets the next line from this box.

The compiler is clever here. Message is as large as the String it may hold (24 bytes) and fits the tag in unused bit patterns of the String (a niche). Option<Box<u32>> needs no tag at all: a Box is never null, so None is stored as the null pointer. Niche optimization is the reason Option<&T> costs nothing over &T. If one variant is huge and others tiny, every value pays for the huge one; box that variant's data (Big(Box<BigData>)) to shrink the enum. Memory Layout and Sizes digs deeper.

A state machine

Enums with data are ideal for state machines because a state carries exactly the data that makes sense in it:

Rust An order 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 io::stdin().read_line()), it gets the next line from this box.

Each transition takes self by value and returns the next state, so the old state is gone and cannot be used by mistake. The .. pattern ignores the fields you do not need.

When to use an enum

  • The value is one of a closed set of alternatives you control: commands, tokens, shapes, states, errors.
  • Different alternatives need different data.
  • You want the compiler to force every match to handle new alternatives.

Use a struct when you have several values at once, and a trait object (Trait Objects and Dynamic Dispatch) when other people must be able to add new alternatives without editing your enum.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes a Rust enum different from a C enum?

    Variants can be tuple-like or struct-like and hold different data, which is why Rust enums are called sum types or algebraic data types.
  2. 2. What happens when a match on an enum forgets a variant?

    match must be exhaustive. The compiler names the uncovered variant, which makes adding variants later safe.
  3. 3. Given enum Level { Low, Medium, High }, what is Level::High as u8?

    Discriminants start at 0 and count up, so Low is 0, Medium is 1 and High is 2.
  4. 4. Why is Option<Box<u32>> the same size as Box<u32>?

    Niche optimization stores None in a bit pattern that a valid Box can never have, so no extra tag is needed.
  5. 5. What is an Option<T> in the standard library?

    Option is defined as enum Option<T> { None, Some(T) }; nothing about it is built into the language except its prelude name.

Summary

  • An enum is a value that is exactly one of several variants; variants can be unit, tuple-like or struct-like.
  • match must cover every variant (E0004), which makes enum-based code easy to refactor.
  • Option<T> and Result<T, E> are ordinary enums.
  • Enums can have impl blocks; match self is the standard pattern.
  • C-like enums have integer discriminants that you can set and read with as; going back needs match or TryFrom.
  • An enum is as large as its biggest variant plus a tag; niches can remove the tag.
  • Model state machines by letting each variant hold only the data valid in that state.

Next: Modelling with Enums and Pattern Matching