Skip to content

Borrow Checker allowing mutable and immutable reference out on a vec [Nightly] #41774

Closed
@mooman219

Description

@mooman219

When using array indexing, the borrow checking is allowing for both an immutable and mutable reference to be taken out on a vec.

Playground: https://play.rust-lang.org/?gist=558d7e98834c5e269eed35b335823220&version=nightly&backtrace=0

Version: rustc 1.19.0-nightly (59f1a2f 2017-05-04)

Offending Code:

#[derive(Debug)]
struct Data {
    x: i32,
    y: i32,
}

impl Data {
    fn add(&mut self, other: &Data) -> &mut Data {
        self.x += other.x;
        self.y += other.y;
        return self;
    }
}

fn main() {
    let mut v = vec![
        Data{x: 0, y: 1},
        Data{x: 2, y: 3},
        Data{x: 4, y: 5},
    ];
    v[0].add(v[1].add(&v[2]));

    println!("{:?}", v);
}

Expected Result:

error[E0499]: cannot borrow `v` as mutable more than once at a time
  --> <anon>:21:14
   |
21 |     v[0].add(v[1].add(&v[2]));
   |     -        ^              - first borrow ends here
   |     |        |
   |     |        second mutable borrow occurs here
   |     first mutable borrow occurs here

error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
  --> <anon>:21:24
   |
21 |     v[0].add(v[1].add(&v[2]));
   |     -                  ^    - mutable borrow ends here
   |     |                  |
   |     |                  immutable borrow occurs here
   |     mutable borrow occurs here

Actual Result:
[Data { x: 6, y: 9 }, Data { x: 6, y: 8 }, Data { x: 4, y: 5 }]

Metadata

Metadata

Assignees

No one assigned

    Labels

    I-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.regression-from-stable-to-nightlyPerformance or correctness regression from stable to nightly.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions