Between the two snippets below, which is the better / preferred one?
fn main() {
let pair = 7;
match pair {
pair if pair > 5 => println!("Yeah"),
_ => println!("No"),
}
}
fn main() {
let pair = 7;
match pair {
_ if pair > 5 => println!("Yeah"),
_ => println!("No"),
}
}
And is there a better way to write this? Because this doesn't work:
fn main() {
let pair = 7;
match pair {
> 5 => println!("Yeah"),
_ => println!("No"),
}
}
You can use pattern matching to test the shape and values of the data instead of transforming it into a set of objects.
Patterns are a special syntax in Rust for matching against the structure of types, both complex and simple. Using patterns in conjunction with match expressions and other constructs gives you more control over a program's control flow.
Pattern matching in computer science is the checking and locating of specific sequences of data of some pattern among raw data or a sequence of tokens. Unlike pattern recognition, the match has to be exact in the case of pattern matching.
For example, x* matches any number of x characters, [0-9]* matches any number of digits, and . * matches any number of anything. A regular expression pattern match succeeds if the pattern matches anywhere in the value being tested.
The version that does not bind the matched variable is preferred:
fn main() {
let pair = 7;
match pair {
_ if pair > 5 => println!("Yeah"),
_ => println!("No"),
}
}
This is the shortest version with a match. Of course, this example could just use an if
.
I'm actually surprised that the first version does not give a warning about unused variables.
Ah, this was me being silly. The variable is used here, in the pattern guard. ^_^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With