liveBook · Manning

Enum

As explained in Write Powerful Rust Macros

An enum is a Rust sum type with a fixed set of named variants that may carry associated data and methods.

An enum is a Rust sum type whose variants represent a restricted set of possible states. Variants can carry data, expose methods, and work naturally with pattern matching. section 7.3

Representing success or failure

Model an operation that either succeeds with a value or fails with a message: `Either<T>` has `Success(T)` and `Failure(String)` variants. A caller must match both possibilities, making failure handling explicit. section 7.3

enum Either<T> {
    Success(T),
    Failure(String),
}

Defines a generic enum with success and failure variants carrying different data. section 7.3

fn calculate_answer_to_life() -> Either<i32> {
    Either::Success(42)
}

fn main() {
    match calculate_answer_to_life() {
        Either::Success(answer) => {
            println!("Got the answer: {answer}");
        }
        Either::Failure(_) => {
            println!("Should handle failure");
        }
    }
}

Uses pattern matching to extract a successful answer and handle failure. section 7.3

impl<T> Either<T> {
    fn map(self, function: fn(T) -> T) -> Either<T> {
        match self {
            Either::Success(answer) => {
                return Either::Success(function(answer))
            }
            // if it's not a success, no need to do anything
            _ => self
        }
    }
}

fn main() {
    let two = Either::Success(1).map(|v| v + 1);
}

Adds a `map` method that transforms a success value while leaving failures unchanged. section 7.3

How Write Powerful Rust Macros covers it

How deep it goes
Explains variants, associated data, pattern matching, generics, and a convenience method without descending into representation internals.
Examples
Uses an `Either<T>` result, a calculation returning `Success(42)`, exhaustive matching, and a `map` transformation.
What you can do after
Apply enums to represent recoverable outcomes and handle each variant through pattern matching.
How it connects
Connects sum types with pattern matching, product types, generics, methods, and error handling.

Also explained in

Compare how 23 books explain enum →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.