rust-lang / rust-lang/rust

Pattern matching reborrowing

Open
#123,543 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-patterns C-discussion S-has-mcve T-compiler T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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);
        }
    }
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by compiling the not_works and works functions in the reproducer and compare their pattern-matching behavior. Investigate why the @ binding causes the mutable-borrow error while the nested match succeeds; done means establishing consistent, accepted behavior for the equivalent patterns and covering the case with a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.