liveBook · Manning

Either

As explained in Write Powerful Rust Macros

Either is a sum-type pattern representing one of two alternatives, conventionally a successful result or a failure.

Either represents a result with exactly two alternatives: Success containing a value or Failure containing an error message. As a sum type, it makes success-or-failure states explicit and gives Rust's pattern matching a clear target. section 7.3

A minimal Either-based workflow:

  • Define enum Either<T> with Success(T) and Failure(String) variants. section 7.3
  • Return Either from a calculation instead of hiding whether it succeeded. section 7.3
  • Match on the variants to handle the result explicitly. section 7.3
  • Map a successful value while leaving failures unchanged. section 7.3
enum Either<T> {
    Success(T),
    Failure(String),
}

Inspect the compact enum definition that gives Either its two-state structure. section 7.3

How Write Powerful Rust Macros covers it

How deep it goes
Defines a generic enum and demonstrates matching plus mapping, connecting the representation to practical handling.
Examples
Uses a calculate_answer_to_life function returning Success(42), a match expression, and a map transforming one into two.
What it assumes
Introduces sum types by contrasting them with product types such as structs.
What you can do after
Build it from scratch by defining Either, returning it from functions, matching its variants, and mapping successful values.
How it connects
Connects algebraic data types, sum types, enums, pattern matching, and error handling.

Also explained in

Compare how 4 books explain Either →

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.