Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the preferred way of matching a variable with a pattern guard that doesn't use the matched value?

Tags:

rust

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"),
    }
}
like image 791
Mathieu David Avatar asked May 30 '15 12:05

Mathieu David


People also ask

What pattern matching allows us?

You can use pattern matching to test the shape and values of the data instead of transforming it into a set of objects.

What is pattern matching in Rust?

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.

What is pattern matching in programming?

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.

What is pattern matching give an example?

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.


1 Answers

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. ^_^

like image 144
Shepmaster Avatar answered Sep 22 '22 23:09

Shepmaster