educative.io

Pattern matching in if let expression

Here is the note:

Note: When it says matching of pattern, it means that the defined pattern has the same number of values as that of the scrutinee expression.

but actual pattern matching performed by content of values, not the number?

Hi @Arseny_Bondarenko !!
In Rust, the if let construct is indeed a conditional expression that allows pattern matching. However, the statement you made about the pattern matching based on the content of values rather than the number is not entirely accurate.

When using the if let expression in Rust, the pattern matching is performed based on both the structure and the content of the values. The pattern must match both the structure and the content of the scrutinee expression for the code block to execute.
In this expression, if let ("value 1", "value 2") = matching_expression, suggests that we are trying to match a tuple pattern against the matching_expression in Rust.

However, it’s important to note that matching a tuple pattern in this way doesn’t involve comparing the values by their content. Instead, it checks if the structure of the tuple matches the pattern.

let tuple = ("value 1", "value 2");

if let ("value 1", "value 2") = tuple {
    println!("Pattern matched");
}

In this example, the pattern ("value 1", "value 2") is matched against the tuple variable. The pattern matches because the structure of the tuple in tuple is the same as the pattern. It doesn’t matter what the actual values are; the pattern only checks the structure.

If the pattern did not match the matching_expression, the code block within the if let construct would not execute. Alternatively, you can provide an optional else block to specify code that should execute when the pattern does not match.

I hope it helps. Happy Learning :blush: