Skip to content

if let binding in match guard #2214

Closed
Closed
@jvff

Description

@jvff

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-langRelevant to the language team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions