0
0
Rustprogramming~5 mins

Destructuring patterns in Rust

Choose your learning style9 modes available
Introduction

Destructuring patterns let you take apart complex data like tuples or structs into smaller pieces easily.

When you want to get values out of a tuple or struct quickly.
When you want to name parts of a complex value for easier use.
When you want to check the shape of data and get parts at the same time.
When you want to write clear code that shows what parts you need.
When you want to handle different data shapes in match statements.
Syntax
Rust
let (a, b) = (1, 2);
let Point { x, y } = point;
match value {
    Some(x) => println!("Got {}", x),
    None => println!("No value"),
}

You use let with a pattern on the left to break down values.

Patterns can be tuples, structs, enums, or simple variables.

Examples
Break a tuple into two variables x and y.
Rust
let (x, y) = (10, 20);
println!("x = {}, y = {}", x, y);
Extract fields from a struct by naming them in the pattern.
Rust
struct Point { x: i32, y: i32 }
let p = Point { x: 5, y: 7 };
let Point { x, y } = p;
println!("x = {}, y = {}", x, y);
Use destructuring in a match to get the value inside an Option.
Rust
let some_value = Some(42);
match some_value {
    Some(num) => println!("Number: {}", num),
    None => println!("No number"),
}
Sample Program

This program shows destructuring a struct, a tuple, and an enum Option to get values out easily.

Rust
struct Person {
    name: String,
    age: u8,
}

fn main() {
    let person = Person { name: String::from("Alice"), age: 30 };
    let Person { name, age } = person;
    println!("Name: {}, Age: {}", name, age);

    let coords = (3, 7);
    let (x, y) = coords;
    println!("x = {}, y = {}", x, y);

    let maybe_number = Some(10);
    match maybe_number {
        Some(n) => println!("Got number: {}", n),
        None => println!("No number"),
    }
}
OutputSuccess
Important Notes

Destructuring helps write clear and concise code by naming parts of data.

You can ignore parts you don't need using underscores _.

Destructuring works well with match to handle different cases.

Summary

Destructuring breaks complex data into simple parts.

Use it with let and match to get values easily.

It works with tuples, structs, enums, and more.