liveBook · Manning

Destructuring assignment

As explained in Idiomatic Rust

Destructuring is the decomposition of a compound value into bindings for selected or constituent parts through a pattern.

Rust uses patterns in `match` expressions to destructure tuples, structs, and enums, binding selected inner values. This treatment demonstrates destructuring through pattern matching, not standalone assignment syntax. section 3.1.1

fn destructure_tuple(tuple: &(i32, i32, i32)) {
    match tuple {
      (first, ..) => {
          println!("First tuple element is {first}")  #1
      }
    }
    match tuple {
      (.., last) => {
          println!("Last tuple element is {last}")  #2
      }
    }
    match tuple {
      (_, middle, _) => {
          println!(
            "The middle tuple element is {middle}"  #3
          )
      }
    }
    match tuple {
      (first, middle, last) => {
          println!("The whole tuple is ({first}, {middle}, {last})")  #4
      }
    }
}

Tuple patterns can bind one element with `..`, select a middle element, or bind every element. section 3.1.1

Struct patterns can select fields while matching a particular field value; enum patterns bind the value inside each variant. These patterns make inner data available to the matching branch. section 3.1.1

How Idiomatic Rust covers it

How deep it goes
Demonstrates partial and complete tuple, struct, and enum destructuring through match patterns.
Examples
Shows tuple element selection, struct field matching, and enum variant bindings.
What you can do after
Apply pattern matching to bind values from tuples, structs, and enum variants.
How it connects
Connects destructuring to pattern matching, match expressions, tuples, structs, enums, and `Option`.

Also explained in

Compare how 6 books explain destructuring assignment →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.