Allow negation in `let else` expressions

The syntax could be something like this:

let !Disabled = feature else { return }

The problem is that when the feature has more than two variants the current syntax becomes unergonomic:

let EnabledA | EnabledB | EnabledC = feature else { return }

We of course can use if let expression in this case:

if let Disabled = feature { return }

But this is kind of less "assertive" than the proposed syntax

I think negation is inappropriate for let else, because it fundamentally can't bind anything, which is the whole point of let else.

Yeah, I tried it get unless let as the syntax, since that allows assertion-like unless x > 0 { continue } and such. But I lost, so it's probably too late for this kind of argument.

6 Likes

If you don't need to bind anything (and you can't for a negative), then matches! is likely what you want rather than let, e.g.

if matches!(feature, Disabled) { return }

While it's generally not recommended, you can turn this into a let-else as

let false = matches!(feature, Disabled) else { return }

but this is nesting multiple levels of negation.

I don't know one off the top of my head, but there's certainly crates out there offering assert_or! style macros as well.

There's probably no way it'd be added to Rust, but it'd be certainly be interesting to just allow $bool_expr else $diverging_block generally.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.