Sum Type
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."
Related Terms
Algebraic Data Types
Algebraic data types are like Lego for type systems.
Discriminated Union
A discriminated union is like a box that could contain a cat, a dog, or a fish — but it has a label on the outside telling you which one.
Product Type
A product type is 'this thing has a name AND an age AND an email — all at once.' It's your everyday struct or object.
Result Type
Result type is like a delivery that's either your package (Ok) or a note explaining why it failed (Err).