Advanced Pattern Matching
Destructure Enum
Pull Fields from Variants
Pattern matching can unpack enum variants and bind the fields needed by each arm.
Program
Play the program to choose a command kind and watch the matching arm destructure it.
destructure_enum.rs
fn main() {
let kind = ;
let command = make_command(kind);
let text = describe(command);
println!("{text}");
}
enum Command {
Move { x: i32, y: i32 },
Wait(i32),
Quit,
}
fn make_command(kind: i32) -> Command {
match kind {
1 => Command::Move { x: 3, y: 4 },
2 => Command::Wait(5),
_ => Command::Quit,
}
}
fn describe(command: Command) -> String {
match command {
Command::Move { x, y } => format!("move:{x},{y}"),
Command::Wait(seconds) => format!("wait:{seconds}"),
Command::Quit => "quit".to_string(),
}
}
fn main() {
let kind = ;
let command = make_command(kind);
let text = describe(command);
println!("{text}");
}
enum Command {
Move { x: i32, y: i32 },
Wait(i32),
Quit,
}
fn make_command(kind: i32) -> Command {
match kind {
1 => Command::Move { x: 3, y: 4 },
2 => Command::Wait(5),
_ => Command::Quit,
}
}
fn describe(command: Command) -> String {
match command {
Command::Move { x, y } => format!("move:{x},{y}"),
Command::Wait(seconds) => format!("wait:{seconds}"),
Command::Quit => "quit".to_string(),
}
}
fn main() {
let kind = ;
let command = make_command(kind);
let text = describe(command);
println!("{text}");
}
enum Command {
Move { x: i32, y: i32 },
Wait(i32),
Quit,
}
fn make_command(kind: i32) -> Command {
match kind {
1 => Command::Move { x: 3, y: 4 },
2 => Command::Wait(5),
_ => Command::Quit,
}
}
fn describe(command: Command) -> String {
match command {
Command::Move { x, y } => format!("move:{x},{y}"),
Command::Wait(seconds) => format!("wait:{seconds}"),
Command::Quit => "quit".to_string(),
}
}
enum variant
`Command::Move { x, y }` matches one variant and binds its fields.
tuple variant
`Command::Wait(seconds)` binds the single value inside a tuple-like variant.
ownership
`describe` takes ownership of the command and consumes it while matching.