Stable since November 3, 2022, Rust’s let-else is a bit of an odd one (RFC).

As defined by the linked Rust by Example docs above:

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.

The RFC doc more formally defines it as:

let PATTERN: TYPE = EXPRESSION else DIVERGING_BLOCK;

and notes that this is the the counterpart of if-let expressions which we covered in a previous post.

Essentially, we are attempting to bind some expression to some type and if this is “non-bindable”, then execute the diverging block.

In generalized DTR, we’d get something like this:

{ instruction: evaluate, input: (SOME_EXPRESSION), assign: SOME_EXPRESSION_RESULT, scope: 0 }
{ instruction: evaluate, input: (try_assign, SOME_EXPRESSION_RESULT, SOME_TYPE), assign: SUCCESSFUL_ASSIGN_RESULT, scope: 0 }
{ instruction: jump, input: (SUCCESSFUL_ASSIGN_RESULT, 1), scope: 0 }
{ instruction: jump, input: (2), scope: 0 }
{ instruction: jump, input: (0), scope: 1 } // effectively "jump" over the diverging block
*** DIVERGING BLOCK at scope 2 ***
{ instruction: jump, input: (0), scope: 2 }

Specific Example

For a specific example, consider the following rust code:

fn get_count_item(s: &str) {
    let Ok(foobar) = ok_foobar else {
        panic!("Can't parse ok foobar");
    };
}

We can then translate this to DTR leveraging the notion of a try_assign from the if-let post.

// [0] let Ok(foobar) = ok_foobar
{ instruction: evaluate, input: (try_assign, Ok(foobar), ok_foobar), assign: SUCCESSFUL_ASSIGN_RESULT, scope: 0 }
// [0] if let ..., scope = 1
{ instruction: jump, input: (SUCCESSFUL_ASSIGN_RESULT, 1), scope: 0 }
// [0] else, scope = 2
{ instruction: jump, input: (2), scope: 0 }
// [1] scope = 0
{ instruction: jump, input: (0), scope: 1 }
// [2] panic!("Can't parse ok foobar");
{ instruction: exit_with_message, input: ("\"Can't parse ok foobar\""), scope: 2}

Note: here we don’t have to “jump back to scope 0” since exit_with_message is a terminal instruction.