rust-lang / rust-lang/rust

Borrow checking false positive on inferred closure type and borrowed fields

Open
#152,526 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-borrow-checker C-bug needs-triage
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

The minimal example constructed so far:

#[derive(Default)]
struct A {
    a: Vec<u32>,
    b: Vec<u32>,
}
fn main() {
    let mut a = A::default();
    let f = if true {
        |_v| vec![]
    } else {
        |_v: &Vec<u32>| vec![0_u32]
    };
    let u = f(&a.a);
    a.a = u;
    f(&a.b);
}

(Playground)

Errors:

   Compiling playground v0.0.1 (/playground)
error[E0506]: cannot assign to `a.a` because it is borrowed
  --> src/main.rs:14:5
   |
13 |     let u = f(&a.a);
   |               ---- `a.a` is borrowed here
14 |     a.a = u;
   |     ^^^ `a.a` is assigned to here but it was already borrowed
15 |     f(&a.b);
   |     - borrow later used here

For more information about this error, try `rustc --explain E0506`.
error: could not compile `playground` (bin "playground") due to 1 previous error

while the following modifications wouldn't anger the borrow checker and compiles:

  • Using Vec directly: let a = vec![]
  • Removing if: let f = |v: &Vec<u32>| vec![0_u32]
  • Fully annotating the types: if true { |_v: &Vec<u32>| ...
  • Removing f(&a.b)

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

Reproduce the minimal example in src/main.rs, starting with the inferred closure type and the borrow of a.a. Compare it with the listed compiling modifications, then verify that the original example no longer reports E0506 while the later call using a.b remains valid.

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.