← Back to Rust Course | Chapter 8: Enums & Pattern Matching | Lesson 7 of 7

Destructuring

Destructuring is unpacking a value into separate named pieces all at once, like opening a gift box and taking out each item.

Destructuring a Tuple

A let statement can destructure a tuple directly into multiple named variables in one line, instead of accessing each element with .0, .1, and so on.

Example: Destructuring a Tuple

markup
fn main() {
    let point = (3, 7);
    let (x, y) = point;
    println!("x={}, y={}", x, y);
}

Destructuring a Struct

Struct fields can be destructured into local variables of the same names directly in a let statement, using the struct's field names as the pattern.

Example: Destructuring a Struct

markup
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 5, y: 9 };
    let Point { x, y } = p;
    println!("x={}, y={}", x, y);
}

Ignoring Fields with ..

When you only need a few fields from a larger struct, .. in the pattern tells Rust to ignore all remaining fields without naming them individually.

Example: Ignoring Fields with ..

markup
struct Config {
    width: u32,
    height: u32,
    fullscreen: bool,
}

fn main() {
    let cfg = Config { width: 1920, height: 1080, fullscreen: true };
    let Config { width, .. } = cfg;
    println!("Width: {}", width);
}

Discarding Values with _

The underscore pattern _ matches any value while discarding it, useful in destructuring or function parameters when a value must be present but is not actually needed.

Example: Discarding Values with _

markup
fn main() {
    let (first, _, third) = (1, 2, 3);
    println!("first={}, third={}", first, third);
}
Common Mistakes
  1. Trying to destructure only some fields of a struct without using .. to explicitly ignore the rest, which is a compile error.
  2. Forgetting the _ pattern can be used to intentionally discard a value you don't need during destructuring.
  3. Assuming destructuring a reference automatically dereferences everything -- sometimes an explicit & pattern or .clone() is needed.
Chapter Summary
  • Destructuring extracts multiple named values from a tuple, struct, or enum in a single let or match.
  • The .. pattern can be used to ignore remaining fields you don't care about.
  • The _ pattern matches and discards any single value without binding it to a name.
  • Destructuring works in let statements, function parameters, and match arms alike.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.