rust-lang / rust-lang/rust

Strange behavior of borrow checker

Open
#148,897 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-borrow-checker C-bug fixed-by-polonius T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

fn test() {
    let a_mut = &mut ();
    let mut a = &*a_mut;
    let temp = a;
    a = &();
    do_smth(temp);
    *a_mut = ();
    do_smth(a);
}
fn do_smth(_: &()) {}

And this:

fn test() {
    let a_mut = &mut ();
    let mut a = &*a_mut;
    let temp = a;
    do_smth(temp);
    a = &();
    *a_mut = ();
    do_smth(a);
}
fn do_smth(_: &()) {}

I expect both options to work. But only the second option works. It’s strange that if you swap the lines “do_smth(temp)” and “a = &()”, then everything starts to work. In both variants, the essence of the code is preserved: after "*a_mut = ()" the variable "temp" is no longer used, and the variable "a" is not associated in lifetime with the variable "a_mut", so borrow checker can ignore them. But the results of the borrow checker are different in these two cases. I wonder why?

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 two test examples and comparing the borrow-checker diagnostics when do_smth(temp) and a = &() are reordered. Trace the compiler's borrow-checking treatment of a_mut, a, and temp; done means the differing behavior is explained and, if incorrect, covered by 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
Active
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.