RRust By Example
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

Extract values from structs and enums with patterns.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the patterns category to build a complete understanding of this topic.

More Patterns Examples