CodeBlanks Logo Icon CodeBlanks

Value binding

Bind matched values with pattern variables.

Binding values

Patterns can take values apart (destructure) and bind them to variables. Tuples, structs and enums are unpacked the same way:

let nokta = (3, 0);
match nokta {
    (0, 0) => println!("merkez"),
    (x, 0) => println!("x ekseni {x}"),
    (0, y) => println!("y ekseni {y}"),
    (x, y) => println!("{x},{y}"),
}

Literal parts narrow the match, variable parts capture the value.

Struct destructuring and @

Struct fields are unpacked by name; .. ignores the remaining fields. name @ pattern both checks the pattern and binds the value:

struct Oyuncu { ad: String, puan: u32 }

let o = Oyuncu { ad: String::from("Ece"), puan: 87 };
match o {
    Oyuncu { puan: p @ 80..=100, .. } => println!("usta: {p}"),
    Oyuncu { ad, .. } => println!("{ad} çalışmalı"),
}

Practice Classify points

Loop over the array [(0, 0), (3, 0), (0, 5), (2, 2)] and classify each point with match: merkez, x ekseni N, y ekseni N or x,y. Print each result on its own line.

Starter code

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

Sample solution

main.rs
fn main() {
    let noktalar = [(0, 0), (3, 0), (0, 5), (2, 2)];
    for n in noktalar {
        match n {
            (0, 0) => println!("merkez"),
            (x, 0) => println!("x ekseni {}", x),
            (0, y) => println!("y ekseni {}", y),
            (x, y) => println!("{},{}", x, y),
        }
    }
}

Expected output

merkez
x ekseni 3
y ekseni 5
2,2

Questions and answers

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

1 Which arm does <code>match (0, 7) { (x, 0) =&gt; .., (0, y) =&gt; .., _ =&gt; .. }</code> take?

  • (0, y) with y = 7 Correct answer
  • (x, 0) with x = 0
  • _
  • None

Explanation: The first arm doesn't fit because the second element isn't 0; the second arm fits because the first element is 0.

2 Bind the range

Question
match yas {
    n ____ 0..=17 => println!("{n}: çocuk"),
    n => println!("{n}: yetişkin"),
}
Answer
match yas {
    n @ 0..=17 => println!("{n}: çocuk"),
    n => println!("{n}: yetişkin"),
}

Explanation: @ both checks the range and binds the matching value to n.

3 Pattern and meaning

Term Meaning
(x, 0) Second element 0, x is bound
Oyuncu { ad, .. } Only the ad field
p @ 80..=100 Range + binding
(_, y) The first is ignored

All lessons in Beginner