Rfcs: Allow `if <cond> { ... } else match { ... }`

Created on 28 Nov 2020  路  5Comments  路  Source: rust-lang/rfcs

We allow else if so it's a pretty natural extension to support else match too. In fact I've often forgotten that this is not supported...

Example:

fn main() {
    let x = 1;
    let y = 2;
    if x == 2 {
        // Do something
    } else match y {
        1 => {},
        _ => {}
    }
}
T-lang

Most helpful comment

This was proposed some time ago see https://github.com/rust-lang/rfcs/pull/2901

All 5 comments

This was proposed some time ago see https://github.com/rust-lang/rfcs/pull/2901

Ah I didn't find this when I was looking for existing proposals.

One reason why this makes sense for match is that if let is normally documented as syntax sugar for a two-arm match statement, but we allow else if let ... and not else match ... which seems inconsistent...

In general, I would be in favour of allowing any scope-introducing statement (while, loop, for, etc.) to follow an else directly, although else match seems like a good first step.

As mentioned there, (else) if let is viable as a single branch always. else match becomes incoherent with the ordinary if { } else if { } else { } syntax because it must be the terminating branch. This introduces more special casing in parsing so while it may add one kind of consistency it reduces other kinds of consistency, and as such is not a clearly desirable addition and needs a stronger argument for it.

What about this?

fn main() {
    let x = 1;
    let y = 2;
    match y {
        _ if x == 2 => do_something(),
        1 => {},
        _ => {}
    }
}

Yes, that's idiomatic at least when the first y matches anything more than _.

Imho, we should complicate syntax to prevent rightward drift because rightward drift can always be addressed by bracket conventions.

if foo {
    ...
} else if bar {
    .. 
} else { match baz {
    .. => ..
} }

This is not the greatest example, but bracket conventions usually improve readability considerably, like the double bracketing makes the closure more visible while avoiding rightward drift in

foo(|x,y| {
    ...
} );
Was this page helpful?
0 / 5 - 0 ratings

Related issues

burdges picture burdges  路  3Comments

silversolver1 picture silversolver1  路  3Comments

mqudsi picture mqudsi  路  3Comments

3442853561 picture 3442853561  路  3Comments

steveklabnik picture steveklabnik  路  4Comments