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)