CodeBlanks Logo Icon CodeBlanks

@ binding

Bind a value range with the @ operator.

@ binding

name @ pattern checks a value against the pattern while binding it to a variable at the same time. It's handy with ranges and nested patterns:

fn basamak(n: u32) -> String {
    match n {
        k @ 0..=9 => format!("tek basamak {k}"),
        k @ 10..=99 => format!("iki basamak {k}"),
        k => format!("büyük {k}"),
    }
}

match opt {
    Some(x @ 1..=5) => println!("küçük: {x}"),
    Some(x) => println!("diğer: {x}"),
    None => {}
}

Without @, a range pattern wouldn't bind the value and the arm would have to reuse n.

Together with |

@ works with patterns that have several alternatives too; all alternatives must bind the same variable:

match karakter {
    c @ ('a' | 'e' | 'ı' | 'i' | 'o' | 'ö' | 'u' | 'ü') => println!("sesli {c}"),
    c @ ('0'..='9') => println!("rakam {c}"),
    c => println!("diğer {c}"),
}

Practice Digit class

Write the basamak function above with @ bindings. Print the results for 7, 42 and 500 on separate lines.

Starter code

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

Sample solution

main.rs
fn basamak(n: u32) -> String {
    match n {
        k @ 0..=9 => format!("tek basamak {k}"),
        k @ 10..=99 => format!("iki basamak {k}"),
        k => format!("büyük {k}"),
    }
}

fn main() {
    for n in [7, 42, 500] {
        println!("{}", basamak(n));
    }
}

Expected output

tek basamak 7
iki basamak 42
büyük 500

Questions and answers

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

1 What does the pattern <code>e @ Mesaj::Yaz(_)</code> bind?

  • It doesn't compile
  • The whole Mesaj::Yaz value to e Correct answer
  • Only the inner text
  • Nothing

Explanation: @ binds the whole value; if the inner part is needed too, they can be written together like e @ Mesaj::Yaz(ref m).

2 Bind with a range

Question
match n {
    k ____ 0..=9 => format!("tek basamak {k}"),
    k => format!("{k}"),
}
Answer
match n {
    k @ 0..=9 => format!("tek basamak {k}"),
    k => format!("{k}"),
}

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

3 Number and basamak result

Term Meaning
7 tek basamak 7
42 iki basamak 42
500 büyük 500
0 tek basamak 0

All lessons in Advanced