I'm new in Rust and while learning the standard library I found the expression Some(x @ 6..=10) in a match example. What does x @ 6..=10 mean?
- 13,874
- 15
- 47
- 98
- 21
- 2
-
1Why won't [google](https://doc.rust-lang.org/1.8.0/book/patterns.html#bindings) first? – Alexey S. Larionov Jan 23 '21 at 12:56
3 Answers
something @ pattern is a way to do the pattern matching. Normally a match branch creates variables for parts of the matched value. But something @ pattern creates a variable something and moves or copies the whole value into it.
- 26,690
- 50
- 155
- 234
The syntax low ..= high allows you to match on all numbers within the range from low to high (inclusive). The @ in pattern match expressions allows you to bind a variable to the matched value. Here's an example to illustrate their uses:
fn log_num(maybe_num: Option<i32>) {
match maybe_num {
None => println!("didn't get a number"),
Some(x @ 0..=5) => println!("got number {} between 0-5", x),
Some(y @ 6..=10) => println!("got number {} between 6-10", y),
Some(z) => println!("got number {} larger than 10", z),
}
}
fn main() {
log_num(None);
log_num(Some(3));
log_num(Some(7));
log_num(Some(15));
}
- 13,874
- 15
- 47
- 98
This is a form of pattern matching, specifically @ bindings. In the form...
let y = Some(3);
if let Some(x @ 6..=10) = y {
// ...
}
... the variable y needs to be a Some(...) to match, and the inner value will be assigned to x if it is within the range 6 to 10 (inclusive). In the example above, the if-block will not be executed, because while y destructures to a Some(...), the inner value does not fit the pattern and therefor x does not bind.
- 13,636
- 2
- 46
- 67