I'm new to Rust and this is basically the first Rust code I'm trying to write. Below is a simplified version of the problematic code I'm working on, but the errors are exactly the same.
struct A {
pub value : i32
}
impl A {
pub fn new() -> Self {
A {value : 0}
}
}
struct B {
vec_a : Vec<A>
}
impl B {
pub fn new() -> Self {
B {
vec_a : Vec::new()
}
}
pub fn create_A(&mut self) -> &mut A {
let a = A::new();
self.vec_a.push(a);
let last_index = self.vec_a.len() - 1;
&mut self.vec_a[last_index]
}
}
fn main() {
let mut b = B::new();
let a1 : &mut A = b.create_A();
let a2 : &mut A = b.create_A();
println!("{}, {}", a1.value, a2.value);
}
The code gives below compilation error:
error[E0499]: cannot borrow `b` as mutable more than once at a time
--> src/main.rs:32:23
|
31 | let a1 : &mut A = b.create_A();
| ------------ first mutable borrow occurs here
32 | let a2 : &mut A = b.create_A();
| ^^^^^^^^^^^^ second mutable borrow occurs here
33 |
34 | println!("{}, {}", a1.value, a2.value);
| -------- first borrow later used here
It seems to me that the compiler is telling me that the using of a1 is not safe as it is generated from b, and yet there is another mutable borrow of b after a1, that may change b, so that the data in a1 is invalid now. Am I understanding this error correctly? If so, how do I tell the compiler a1 and a2 are completely different part of b and using a1 later on is fine?