Understanding if-let

FYI, if there isn't an else block, then the value of the else block is just unit, i.e. ().

So

if let <PATTERN> = <EXPRESSION> {
    <STATEMENTS>
} // no `else` block

is equivalent to

match <EXPRESSION> {
    <PATTERN> => {
        <STATEMENTS>
    }
    _ => {}
}

or

match <EXPRESSION> {
    <PATTERN> => {
        <STATEMENTS>
    }
    _ => (),
}

and also, in this case, the block with <STATEMENTS> cannot have a block-final-expression "return value" (or if they do, it must be of type () ).

Although... perhaps you haven't even considered if let that evaluates to a value. Let's look at an example:

let x: Option<i32> = ……;

let x_plus_one_or_zero = if let Some(value) = x {
    value + 1
} else {
    0
};

which of course is equivalent to doing

let x_plus_one_or_zero = match x {
    Some(value) => {
        value + 1
    }
    _ => {
        0
    }
}

or, if we skip the {}-braces for the match arms:

let x_plus_one_or_zero = match x {
    Some(value) => value + 1,
    _ => 0,
};
3 Likes

Besides being less typing than a match statement, the if-let syntax also supports chaining. I found this really invaluable for AST traversal:

4 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.