Click a card to flip it · 8 terms
An enum is a type that can represent one of several named variants. This deck covers creating enums, storing data inside variants, and using them to model different states safely.
A type that can be exactly one of several named options.
Subscription status, payment state, instruction types, any fixed set of possibilities.
enum Status { Active, Expired, Pending,}
One of the named options inside an enum.
Creating or matching on an enum value. Each variant is one possibility.
Status::ActiveStatus::Expired
How you refer to a specific enum variant. Type name, then ::, then the variant name.
Every time you create or compare an enum value.
let s = Status::Active;let d = Direction::North;
An integer Rust assigns to each variant automatically, starting at 0.
Lets you convert a variant to a number with as.
Direction::North as u8 // 0Direction::South as u8 // 1
An enum variant with no data. Just a named state.
When one option simply means 'this happened' with no extra information.
enum Command { Quit, // unit variant, no data Pause,}
An enum variant that holds unnamed values in parentheses.
When a variant needs to carry data but named fields are unnecessary.
enum Message { Write(String), Move(i32, i32),}
An enum variant with named fields in curly braces.
When the data inside a variant is complex enough to benefit from names.
enum Message { Move { x: i32, y: i32 },}
Pulling data out of an enum variant right inside a match arm.
When your enum variants carry data you need to use.
match msg { Message::Move { x, y } => println!("{} {}", x, y),}