Skip to content

Pattern matching reborrowing #123543

Open
Open
@Ddystopia

Description

@Ddystopia

Hello, sometimes you want to work with intermediate variables with pattern matching, but when introducing @ bindings rust gives an error cannot borrow value as mutable more than once at a time value is mutably borrowed by 'a' here. But the same code can be made working if just split it into 2 pattern matches.

struct A(B);
struct B(i32);

fn main() {
    works(A(B(1)));
    not_works(A(B(1)));
}

fn not_works(mut foo: A) {
    if let A(a @ B(b)) = &mut foo {
        *b += 1;
        *a = B(8);
    }
}

fn works(mut foo: A) {
    if let A(a) = &mut foo {
        if let B(b) = a {
            *b += 1;
            *a = B(8);
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-patternsRelating to patterns and pattern matchingC-discussionCategory: Discussion or questions that doesn't represent real issues.S-has-mcveStatus: A Minimal Complete and Verifiable Example has been found for this issueT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions