Algebraic Data Type
Table of Contents
A type formed by combining other types algebraically. Two fundamental forms: product types (all fields present simultaneously) and sum types (exactly one variant present at a time). ADTs with exhaustive pattern matching eliminate entire classes of runtime errors by making the compiler verify that every possible state is handled.
Related: Functional Programming Pattern Matching Enums in Rust Type System
Product Types
All fields must be present simultaneously. The number of possible values is the product of each field's possible values.
// Rust struct — product type
struct Point { x: f64, y: f64 }
// Possible values = f64 × f64
struct User { name: String, age: u32, active: bool }
// Possible values = String × u32 × bool
# Python dataclass — equivalent from dataclasses import dataclass @dataclass class Point: x: float y: float
Tuples are anonymous product types: (i32, bool) has
i32 * 2 possible values.
Sum Types
Exactly one variant is present at a time. The number of possible values is the sum of each variant's possible values.
// Rust enum — sum type
enum Shape {
Circle(f64), // contains one f64
Rectangle(f64, f64), // contains two f64s
Triangle { base: f64, height: f64 }, // named fields
}
// A Shape is Circle OR Rectangle OR Triangle — never more than one
-- Haskell — algebraic data types
data Shape = Circle Double
| Rectangle Double Double
| Triangle Double Double
The Two Most Important ADTs
Option / Maybe
Represents a value that may or may not be present. Replaces null — you cannot use the value without explicitly handling the absent case.
enum Option<T> { Some(T), None }
let name: Option<String> = Some("Alice".to_string());
// Compiler forces you to handle both cases
match name {
Some(n) => println!("Hello, {n}"),
None => println!("No name"),
}
// Convenience methods
name.unwrap_or("unknown".to_string())
name.map(|n| n.to_uppercase())
Result / Either
Represents success or failure. Replaces exceptions — errors are values that must be handled.
enum Result<T, E> { Ok(T), Err(E) }
fn parse_age(s: &str) -> Result<u32, String> {
s.parse::<u32>().map_err(|e| e.to_string())
}
match parse_age("42") {
Ok(age) => println!("Age: {age}"),
Err(e) => println!("Error: {e}"),
}
// Propagate errors with ?
fn process(input: &str) -> Result<String, String> {
let age = parse_age(input)?; // returns Err early if parse fails
Ok(format!("Valid age: {age}"))
}
Pattern Matching and Exhaustiveness
The compiler verifies that every variant is handled — adding a new variant to an enum causes compile errors at every match that doesn't cover it:
fn area(shape: Shape) -> f64 {
match shape {
Shape::Circle(r) => std::f64::consts::PI * r * r,
Shape::Rectangle(w, h) => w * h,
Shape::Triangle { base, height } => 0.5 * base * height,
// Forgetting a variant = compile error
}
}
See Pattern Matching for full detail.
Recursive ADTs
ADTs can reference themselves — the basis of linked lists, trees, and other recursive structures:
// Linked list
enum List<T> {
Cons(T, Box<List<T>>), // Box needed — size must be known
Nil,
}
// Binary tree
enum Tree<T> {
Leaf,
Node { value: T, left: Box<Tree<T>>, right: Box<Tree<T>> },
}
Tips
- ADTs + exhaustive pattern matching is a fundamental shift from defensive programming to making invalid states unrepresentable — the type system enforces correctness
OptionandResultin Rust are ordinary enums, not special language constructs — the same mechanism applies to any enum you define- Python lacks native sum types but
dataclasswith inheritance approximates them; third-party libraries likeattrsprovide more ergonomic ADT patterns - Haskell's type system is built almost entirely on ADTs — studying Haskell for a week gives strong intuition for ADT-based design even if you primarily write other languages