Rfcs: `if let` binding in `match` guard

Created on 10 Nov 2017  路  2Comments  路  Source: rust-lang/rfcs

A discussion in the Rust Lang BR Telegram channel raised a use case where the if guard in a match statement needed to call a split_at method and check one of the results while binding the other (IIRC). The context was that there was a desire to match a struct based on different fields, and in some cases on parts of one of the fields that was a slice.

Slice patterns were suggested as an alternative (an example was posted here: https://play.rust-lang.org/?gist=20432c8157a5bd5d560116a8d7bd4ab0&version=nightly), but we also brainstormed that it would be a nice feature if we could bind inside the guard condition. I suggested that it would be interesting to have an if let guard, that could work as follows:

match something {
    // some initial cases
    // ...

    x if let (&[0, 1], tail) = x.split_at(2) => do_something_with(tail),

    // other cases
    // ..
    _ => println!("No match"),
}

Which would be syntax sugar for something like:

match something {
    // some initial cases
    // ...

    x => {
        if let (&[0, 1], tail) = x.split_at(2) {
            do_something_with(tail)
        } else {
            match x {
                // other cases
                // ...
                _ => println!("No match"),
            }
        }
    }
}

In case it's possible to have no _, i.e., the original match statement is exhaustive, then the generated code could include a _ => unreachable!("expected an exhaustive match case"); inside the inner match statement.

T-lang

Most helpful comment

Searching for => if let in the rust repo gave about 50 hits, which seems enough to justify the feature. The syntax feels like a natural extension of if guards.

All 2 comments

Searching for => if let in the rust repo gave about 50 hits, which seems enough to justify the feature. The syntax feels like a natural extension of if guards.

Closing since an RFC (#2294) has been filed for this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

clarfonthey picture clarfonthey  路  3Comments

p-avital picture p-avital  路  3Comments

burdges picture burdges  路  3Comments

torkleyy picture torkleyy  路  3Comments

steveklabnik picture steveklabnik  路  4Comments