liveBook · Manning

Destructuring assignment

As explained in Refactoring to Rust

Destructuring is the extraction of component values from structured values such as enum variants through pattern matching.

Destructuring extracts values from structured values, such as enum variants, through pattern matching. A match arm binds the contained value while checking which variant is present. section 2.5.1

Extracting an enum payload

An enum can store data in a variant: NotDivisible(i32). Matching FizzBuzzValue::NotDivisible(num) both confirms the variant and binds its i32 payload for printing. Rust therefore prevents direct access without checking the value's variant first. section 2.5.1

Listing 2.26 FizzBuzzValue enum holding a number not divisible by 3 or 5
enum FizzBuzzValue {
  Fizz,
  Buzz,
  FizzBuzz,
  NotDivisible(i32),  #1
}

fn main() {
  for i in 1..101 {
    print_fizzbuzz(i);
  }
}

fn print_fizzbuzz(x: i32) {
  match fizzbuzz(x) {
    FizzBuzzValue::FizzBuzz => {
      println!("FizzBuzz");
    }
    FizzBuzzValue::Fizz => {
      println!("Fizz");
    }
    FizzBuzzValue::Buzz => {
      println!("Buzz");
    }
    FizzBuzzValue::NotDivisible(num) => {  #2
      println!("{}", num);
    }
  }
}

fn fizzbuzz(x: i32) -> FizzBuzzValue {
  if x % 3 == 0 && x % 5 == 0 {
    FizzBuzzValue::FizzBuzz
  } else if x % 3 == 0 {
    FizzBuzzValue::Fizz
  } else if x % 5 == 0 {
    FizzBuzzValue::Buzz
  } else {
    FizzBuzzValue::NotDivisible(x)  #3
  }
}

Trace the complete FizzBuzz example, including the enum payload, destructuring match arm, and value returned by the function. section 2.5.1

How Refactoring to Rust covers it

How deep it goes
Defines payload binding and variant checking through a worked FizzBuzz example, without extending beyond enum matching.
Examples
Uses FizzBuzzValue::NotDivisible(i32) and binds its number as num in a match arm.
What it assumes
Assumes enum and match basics, while demonstrating from zero how a variant payload is declared and extracted.
What you can do after
Apply it via Rust match arms to retrieve enum data safely after confirming the variant.
How it connects
Connects enums, pattern matching, match expressions, and error handling.

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 Refactoring to Rust. The section links point to the parts of the book it draws on.