liveBook · Manning

Algebraic data type

As explained in Write Powerful Rust Macros

An algebraic data type is a composite type formed from product and sum type constructors to represent a defined set of values.

An algebraic data type combines product and sum type constructors to represent a defined set of values. Structs behave like product types, while Rust enums provide sum types whose restricted states work well with pattern matching. section 7.3

The two principal forms are:

  • Product type: combines properties, so possible states multiply; a u8 field and a boolean field allow 512 combinations. section 7.3
  • Sum type: selects among alternatives, so possible states add; Rust enums model these alternatives and support pattern matching. section 7.3

Representing success or failure

A custom enum can make outcomes explicit: Either<T> has Success(T) and Failure(String). Matching on the result forces the caller to distinguish the success path from failure handling.

How Write Powerful Rust Macros covers it

How deep it goes
Defines product and sum types, then demonstrates enum matching and value mapping without developing their full implementation details.
Examples
Uses a u8-and-boolean struct, an Either success/failure enum, matching, and a map operation.
What you can do after
Apply enums and pattern matching to represent and handle explicit success-or-failure outcomes.
How it connects
Connects structs, enums, product types, sum types, pattern matching, and error handling.

Also explained in

Compare how 5 books explain algebraic data type →

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.