I need to implement a struct most like graph maybe with circle. In another post, the simplified codes have been successfully compiled. but here comes a new problem
the original code is as following
struct Unit <'a> {
data: Vec<String>,
ptr_data: Vec<&'a Self>,
}
struct UnitStorage <'a> {
storage: Vec<Box<Unit<'a>>>,
}
impl <'a> UnitStorage <'a> {
fn recusive(&'a mut self, unit: &mut Unit<'a>) {
let new_unit = Box::new(Unit {data: vec![], ptr_data: vec![] });
self.storage.push(new_unit);
unit.ptr_data.push(&self.storage[self.storage.len() - 1]);
}
}
It is compiled successfully as far. but when I tried to next step, here comes a new problem
struct Unit <'a> {
data: Vec<String>,
ptr_data: Vec<&'a Self>,
}
struct UnitStorage <'a> {
storage: Vec<Box<Unit<'a>>>,
}
impl <'a> UnitStorage <'a> {
fn recusive(&'a mut self, unit: &'a mut Unit<'a>) {
for _ in &unit.data { //only here are different with code above
let new_unit = Box::new(Unit {data: vec![], ptr_data: vec![] });
self.storage.push(new_unit);
unit.ptr_data.push(&self.storage[self.storage.len() - 1]);
}
}
}
The compiler complain
error[E0502]: cannot borrow `self.storage` as mutable because it is also borrowed as immutable
--> src/lib.rs:14:13
|
10 | impl <'a> UnitStorage <'a> {
| -- lifetime `'a` defined here
...
14 | self.storage.push(new_unit);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
15 | unit.ptr_data.push(&self.storage[self.storage.len() - 1]);
| ---------------------------------------------------------
| | |
| | immutable borrow occurs here
| argument requires that `self.storage` is borrowed for `'a`
error: aborting due to previous error
And the error not because that unit
has been borrowed at clause for _ in &unit.data
while mut borrowed
at unit.ptr_data.push()
. A simple case has proved it
struct TestA {
data_1: Vec<String>,
data_2: Vec<String>,
}
fn main() {
let a = TestA { data_1: vec![], data_2: vec![] };
for _ in a.data_1 {
a.data_2.push("hello".to_owned());
}
}
It will be compiled sucessfully.
So, why this code snippet does not complie?
I always confused with lifetime in Rust, hope get help in enthusiastic Rust community.
Any help will be appreciated, thanks.