Match in else block without braces?

Not sure if this belongs on this forum, it's more of a language RFC, I guess. Here goes: would it be a problem to allow the last else clause in and if/else chain to be a match without requiring braces? That is:

if cond1 {
} else if cond2 {
} else match expr3 {
   // arms

which is nice and concise and avoids increasing the indent level.

TBH, i don't know if the required braces is stylistic and to avoid ambiguity or a parser limitation, but I like it and it makes sense, it just seems like match warrants an exception in this case for the same reasons that the else block doesn't require braces when it's followed by another if.


You can use if statements in pattern matching to achieve this.

1 Like

Concise != better. It actually looks pretty weird to me. Syntax for the sake of syntax is not something that should be treated lightly.

Instead of an if-else if statement, you could use the wildcard pattern with match guards:

match expr3 {
    _ if cond1 => val1,
    _ if cond2 => expr2,
    ... rest of the arms => { ... }

I like this idea, I actually wrote else match in my code today because it seemed natural.

else if ... is already allowed in place of else { if ... }, and if expressions are a special case of match, so it seems natural to me.

This has come up before in various forms, be it else match or else loop or whatever.

FWIW, I've always thought of this as a separate else if token as part of the broader "chain of ifs" construct. Like how Python spells it elif.

So it's not "you can omit the braces after else", but rather that "else if" is just another thing you can do. Which is useful to keep the indentation from growing for the chain, but that doesn't hold for other constructs.

(Arguably the traditional chain is a bad syntax, and it should be something more like if { cond1 => val1, cond2 => expr2, … } instead, but Rust isn't the place for big changes like that.)