What Are Enums with Data (Tagged Unions) in Rust?

Rust enums with data allow each variant to hold unique fields, enabling a single type to represent multiple distinct states with different associated information.

Enums with data, often called tagged unions, are Rust enumerations where each variant can hold its own unique set of fields. This allows a single type to represent multiple distinct states, each carrying different information, which the compiler enforces via pattern matching.

enum Message {
    Quit,
    Move { x: i32, y: i32 },
    Write(String),
    ChangeColor(i32, i32, i32),
}

let m = Message::Move { x: 10, y: 20 };

match m {
    Message::Quit => println!("Quit"),
    Message::Move { x, y } => println!("Move to {}, {}", x, y),
    Message::Write(text) => println!("Text: {}", text),
    Message::ChangeColor(r, g, b) => println!("Color: {}, {}, {}", r, g, b),
}