liveBook · Manning

Destructuring assignment

As explained in Learn Rust in a Month of Lunches

Destructuring is Rust syntax that binds the components of a composite value to separate variables through a matching pattern.

Destructuring binds the parts of a composite value to separate variables by matching a pattern. With a tuple, let (a, b, c) = values; pulls its three items apart. section 3.1.3

Keep these rules in mind:

  • Make the pattern match the value. A three-item tuple requires three pattern positions; a two-item pattern does not match. section 3.1.3
  • Use _ for a component you want to ignore, as in let (_, b, c) = tuple_of_three;. section 3.1.3
  • Remember ownership: destructuring a tuple of String values moves those values into the new variables. section 3.1.3
  • Apply the same idea to structs, rename bindings with field: new_name, and use .. to ignore remaining fields. section 4.2
  • Place a struct pattern in a function parameter when the function should receive selected fields directly. section 4.2

Selecting tuple values

fn main() { let tuple_of_three = ("one", "two", "three"); let (_, b, c) = tuple_of_three; } The underscore leaves the first item unbound, while b and c receive the second and third values. section 3.1.3

Destructuring a struct

let Person { name: fake_name, real_name, height: cm, happiness, } = papa_doc; This binds the name field to fake_name and height to cm while keeping the other field names as bindings. section 4.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains tuple matching, ignored components, ownership moves, struct renaming, omitted fields, and parameter patterns.
Examples
Demonstrates tuple extraction, underscore omission, renamed Person fields, omitted City fields, and destructured function parameters.
What it assumes
Assumes basic Rust variables and composite values while introducing tuple and struct patterns through small examples.
What you can do after
Apply it in Rust to bind composite values, ignore unwanted parts, rename fields, and destructure function inputs.
How it connects
Connects patterns with tuples, structs, enums, functions, ownership, and move semantics.

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 Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.