Enums in Rust

From the Rust cheat sheet ยท Structs & Enums ยท verified Jul 2026

Enums

Define enums with variants that can hold data.

rust
// Enum with data variants
enum Shape {
    Circle(f64),                    // radius
    Rectangle { width: f64, height: f64 },
    Triangle(f64, f64, f64),        // sides
}

// Use match to handle variants
fn area(shape: &Shape) -> f64 {
    match shape {
        Shape::Circle(r) => std::f64::consts::PI * r * r,
        Shape::Rectangle { width, height } => width * height,
        Shape::Triangle(a, b, c) => { /* ... */ 0.0 }
    }
}
๐Ÿ’ก Option<T> replaces null โ€” Some(value) or None, compiler forces you to handle both
โšก Use matches!(val, Pattern) for quick boolean pattern checks without a full match
๐Ÿ“Œ Each enum variant can hold different types and amounts of data โ€” much more powerful than C enums
๐ŸŸข .unwrap() panics on None โ€” prefer .unwrap_or(), .map(), or if let in production code
enumsoptionmatchvariants

More Rust tasks

Back to the full Rust cheat sheet