CodeBlanks Logo Icon CodeBlanks

Destructuring

Learn tuple and struct destructuring.

Destructuring

Patterns can nest: a struct inside a tuple, a tuple inside an enum... A single pattern unpacks a complex value in one go:

enum Olay {
    Tik { konum: (i32, i32) },
    Tus(char),
}

match olay {
    Olay::Tik { konum: (x, y) } => println!("tık {x},{y}"),
    Olay::Tus(c) => println!("tuş {c}"),
}

let ((a, b), Nokta { x, .. }) = ((1, 2), Nokta { x: 5, y: 9 });

let, function parameters and for loops accept patterns too: fn f(&(a, b): &(i32, i32)), for (i, (ad, puan)) in liste.iter().enumerate().

Unpacking in a loop

Patterns make working with collections of pairs and nested structures very readable:

let puanlar = vec![("ece", (90, 85)), ("can", (70, 95))];
for (ad, (vize, final_)) in &puanlar {
    let ort = (vize + final_) / 2;
    println!("{ad}: {ort}");
}

Since final is reserved as a keyword, the variable name is written final_ (or r#final).

Practice Handle events

Write the Olay enum above. Loop over a vector containing Olay::Tik { konum: (3, 4) } and Olay::Tus('a'), unpacking each event with nested patterns, and print each on its own line.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
enum Olay {
    Tik { konum: (i32, i32) },
    Tus(char),
}

fn main() {
    let olaylar = vec![Olay::Tik { konum: (3, 4) }, Olay::Tus('a')];
    for olay in &olaylar {
        match olay {
            Olay::Tik { konum: (x, y) } => println!("tık {},{}", x, y),
            Olay::Tus(c) => println!("tuş {}", c),
        }
    }
}

Expected output

tık 3,4
tuş a

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which patterns can be used with <code>let</code>?

  • Only identifiers
  • Only tuples
  • Irrefutable patterns that fit every value (tuples, structs). let-else for others Correct answer
  • Every pattern

Explanation: let Some(x) = v; doesn't compile because it doesn't cover None; write let Some(x) = v else { .. };.

2 Nested unpacking

Question
match olay {
    Olay::Tik { konum: ____ } => println!("tık {x},{y}"),
    Olay::Tus(c) => println!("tuş {c}"),
}
Answer
match olay {
    Olay::Tik { konum: (x, y) } => println!("tık {x},{y}"),
    Olay::Tus(c) => println!("tuş {c}"),
}

Explanation: A tuple field is unpacked with the (x, y) pattern.

3 Pattern and what it binds

Term Meaning
((a, b), _) a, b
Olay::Tik { konum: (x, y) } x, y
Nokta { x, .. } Only x
(ad, (vize, final_)) Three variables

All lessons in Advanced