intermediatePatterns
Destructuring Structs
Destructure structs and enums in match arms.
Destructuring Structs
Destructure structs and enums in match arms.
Difficulty
Intermediate
Code
rust
struct Point { x: i32, y: i32 }
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
fn main() {
let p = Point { x: 10, y: 20 };
let Point { x, y } = p;
println!("x={}, y={}", x, y);
let msg = Message::Move { x: 5, y: 10 };
match msg {
Message::Quit => println!("quit"),
Message::Move { x, y } => println!("move to ({}, {})", x, y),
Message::Write(text) => println!("write: {}", text),
}
}Explanation
This example demonstrates how to use destructuring structs in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the patterns category to build a complete understanding of this topic.