Skip to content

if let keeps borrows too long #43407

Closed
@oxalica

Description

Borrows in patterns are kept during the whole if let expression, including the else branch, which is counterintuitive and annoying.
For example, this doesn't compile.

let mut x = Some(1);
if let Some(&ref p) = x.as_ref() {
    // do something with p
} else {
    x = Some(2); // error: x is still borrowed
}

To pass the borrow check, you have to write ugly code like this.

let mut x = Some(1);
let mut flag = false;
if let Some(&ref p) = x.as_ref() {
    // do something with p
} else {
    flag = true;
}
if flag {
    x = Some(2);
}

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regionsC-enhancementCategory: An issue proposing an enhancement or a PR with one.fixed-by-NLLBugs fixed, but only when NLL is enabled.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions