Skip to content

Mutable borrows in an else if after an if let are disallowed #28449

@ftxqxd

Description

@ftxqxd
fn main() {
    let mut f = Some(1);
    if let Some(a) = f {
    } else if f.as_mut().is_some() {}
}

Gives:

<anon>:4:15: 4:16 error: cannot mutably borrow in a pattern guard [E0301]
<anon>:4     } else if f.as_mut().is_some() {}
                       ^
note: in expansion of if let expansion
<anon>:3:5: 4:38 note: expansion site

This is an unexpected result of how if let desugaring works, presumably. It’s unexpected because mutable borrowing is normally allowed in else if conditions, but because if let seems to desugar a following else if into a pattern guard, this is disallowed.

To me it would make more sense for this to be treated like any other else if, and be permitted, or at the very least have a clearer message (because it’s not obvious (and is really just an implementation detail) how an else if condition is a pattern guard).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions