Rust — let-else and matches! Link to heading

I have been learning Rust for more than a year, and I am still discovering new Rust syntax/expression!

let-else Link to heading

I was browsing through regex crate docs and came across this strange let-else syntax:

use regex::Regex;

fn main() {
    let re = Regex::new(r"Hello (?<name>\w+)!").unwrap();
    let Some(caps) = re.captures("Hello Murphy!") else {
        println!("no match!");
        return;
    };
    println!("The name is: {}", &caps["name"]);
}

I am aware of if-let-else syntax but it is my first time seeing this let-else without if. Apparently, this new syntax has been stabilized since 1.65, so it has been about 10-months at the time of writing. Here is document from Rust-by-example:

With let-else, a refutable pattern can match and bind variables in the surrounding scope like a normal let, or else diverge (e.g. break, return, panic!) when the pattern doesn’t match.

So, it seems to be a special case of if-let-else where else branch diverges, i.e., break, return, panic!, and even continue, though not stated in the doc. This makes sense, since in that case, it is not so necessary to create a new scope within if-let branch. So, the regex example above can be rewritten as

use regex::Regex;

fn main() {
    let re = Regex::new(r"Hello (?<name>\w+)!").unwrap();
    if let Some(caps) = re.captures("Hello Murphy!") {
        println!("The name is: {}", &caps["name"]);
    } else {
        println!("no match!");
        return;
    };
}

matches! Link to heading

This is another recent discovery of useful idiom in Rust for me. There is a built-in macro matches! in std module since Rust 1.42. All it does is

Returns whether the given expression matches the provided pattern.

Below are examples straight from the official doc

let foo = 'f';
assert!(matches!(foo, 'A'..='Z' | 'a'..='z'));

let bar = Some(4);
assert!(matches!(bar, Some(x) if x > 2));

These expressions are certainly not necessary per se, but somewhat useful in making the code more concise and terse. I am not sure how comfortable I will be writing these expressions anytime soon, but I certainly shall be able to understand what they mean when I encounter these reading code base!