Enum variants with data
Quick answer
An enum defines a type that can be one of several named variants. Each variant can contain different data, making enums useful for representing alternatives such as a pending delivery or a delivered parcel.
Represent alternatives explicitly
Use unit variants for states with no data, tuple variants for positional data and struct variants for named data. A value has one active variant. A match on that value selects the correct branch and can extract its contents. Unlike a record with unrelated boolean flags, an enum can prevent many contradictory combinations by construction.
enum Delivery { Pending, Delivered(String) }fn describe(state: Delivery) { match state { Delivery::Pending => println!("waiting"), Delivery::Delivered(name) => println!("received by {name}"), }}fn main() { describe(Delivery::Pending); describe(Delivery::Delivered(String::from("Ada")));}Expected stdout (not executed):
waitingreceived by AdaOnly the delivered variant contains a recipient.
enum Shape { Square { side: u32 }, Circle { radius: u32 } }fn main() { let shapes = [Shape::Square { side: 3 }, Shape::Circle { radius: 2 }]; for shape in shapes { match shape { Shape::Square { side } => println!("side {side}"), Shape::Circle { radius } => println!("radius {radius}"), } }}Expected stdout (not executed):
side 3radius 2Each match pattern exposes only the fields belonging to that variant.
Common mistake
Do not model mutually exclusive states as multiple independent booleans unless the combinations are genuinely allowed.
Try it yourself
Define an enum for a light that is Off or On with a brightness u8. Print a description of both variants.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Enum variants with data — practice quiz
Choose one answer per question, then review the explanation.
Which enum variant shape carries named fields?
Can one value of an enum simultaneously be two different active variants?
Given `enum State { Idle, Busy(u32) }`, which expression creates Busy with value 4?