Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

if let binding in match guard #2214

Closed
jvff opened this issue Nov 10, 2017 · 2 comments
Closed

if let binding in match guard #2214

jvff opened this issue Nov 10, 2017 · 2 comments
Labels
T-lang Relevant to the language team, which will review and decide on the RFC.

Comments

@jvff
Copy link

jvff commented Nov 10, 2017

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.

@leoyvens
Copy link

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.

@Centril Centril added the T-lang Relevant to the language team, which will review and decide on the RFC. label Dec 6, 2017
@Centril
Copy link
Contributor

Centril commented Apr 26, 2018

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

@Centril Centril closed this as completed Apr 26, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
T-lang Relevant to the language team, which will review and decide on the RFC.
Projects
None yet
Development

No branches or pull requests

3 participants