0

Mutable references to the vector scores is available to the caller of method get_ref (this might not be a good practice, but trying this snippet for my understanding). As shown in the main function there are now two mutable references to the vector scores.

#[derive(Debug)]
struct Match {
    scores: Vec<u32>,
}

impl Match {
    fn new() -> Match {
        Match { scores: Vec::new() }
    }

    fn push(&mut self, val: u32) {
        self.scores.push(val);
    }

    fn get_ref(&mut self) -> &mut Vec<u32> {
        &mut self.scores
    }
}

fn main() {
    let mut m = Match::new();
    m.push(100);
    m.push(123);
    println!("{:?}", m);

    let t = m.get_ref();
    t.push(99);
    println!("{:?}", m);
    m.push(56);
    println!("{:?}", m);
}

As I understand mutable reference is an exclusive access and the above code should have thrown compiler error, but that is not the case. This prints:

Match { scores: [100, 123] }
Match { scores: [100, 123, 99] }
Match { scores: [100, 123, 99, 56] }

Why does the code not result in any errors? Did I miss something here?

Rust compiler version:

$rustc --version 
rustc 1.50.0 (cb75ad5db 2021-02-10)
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
sateesh
  • 27,947
  • 7
  • 36
  • 45
  • Adding a note in case someone lands up on this question. Took some time for me to realize why this is related to NLL. Referencing "t" again (say adding "println!("{:?}", t)" results in compile error of the form "there are more than one mutable borrows". – sateesh May 06 '21 at 04:08

1 Answers1

0

My understanding is that you are only allowed one mutable reference. In this case you only have one mutable reference to the vector scores which is t while m is just mutable instance of the Match struct which are accounted as different which why this works

khalilw1
  • 174
  • 11