Skip to content

Sum Type

Spicy — senior dev territoryGeneral Dev

ELI5 — The Vibe Check

A sum type is 'this thing is EITHER a cat OR a dog OR a fish — pick one.' It's like a multiple choice question for types. Rust calls them enums, TypeScript calls them union types, and Haskell calls them... well, sum types.

Real Talk

A type that represents a value that can be one of several distinct variants, also known as tagged unions, discriminated unions, or coproducts. The 'sum' refers to the total number of possible values being the sum of values across all variants. Each variant can carry different associated data.

Show Me The Code

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

match fetch_user(id) {
    Ok(user) => println!("Found: {}", user.name),
    Err(e) => println!("Error: {}", e),
}

When You'll Hear This

"Model your API response as a sum type: Success with data OR Error with message — no ambiguity." / "Sum types make illegal states unrepresentable — that's the whole point."

Made with passive-aggressive love by manoga.digital. Powered by Claude.