Hello,
I stop coding with rust for few month and I try to do some simple trick ( At least in C and C++ ^^).
I have the following code in rust
struct A<'x>
{
ref_b : Vec<&'x B<'x>>
}
impl<'x> A<'x>{
pub fn new() -> A<'x>{
A {
ref_b : Vec::default(),
}
}
pub fn push_b(&mut self, b : &'x B<'x>){
self.ref_b.push(b);
}
}
struct B<'x>
{
ref_a : Vec<&'x A<'x>>
}
impl<'x> B<'x>{
pub fn new() -> B<'x>{
B {
ref_a : Vec::default(),
}
}
pub fn push_a(&mut self, a : &'x A<'x>){
self.ref_a.push(a);
}
}
struct C<'x>
{
pub all_a : Vec<A<'x>>,
pub all_b : Vec<B<'x>>,
}
impl<'x> C<'x>{
pub fn new() -> C<'x>{
C {
all_a : Vec::default(),
all_b : Vec::default()
}
}
pub fn add_link_a_b(&mut self, i_a:usize, i_b:usize)
{
let b_ref = &mut self.all_b[i_b];
let a_ref = &mut self.all_a[i_a];
a_ref.push_b(b_ref);
b_ref.push_a(a_ref);
}
}
fn main(){
let mut c = C::new();
c.all_a.push(A::new());
c.all_b.push(B::new());
c.add_link_a_b(0, 0);
}
I have the following well known error:
error: lifetime may not live long enough
--> <source>:50:9
|
38 | impl<'x> C<'x>{
| -- lifetime `'x` defined here
...
46 | pub fn add_link_a_b(&mut self, i_a:usize, i_b:usize)
| - let's call the lifetime of this reference `'1`
...
50 | a_ref.push_b(b_ref);
| ^^^^^^^^^^^^^^^^^^^ argument requires that `'1` must outlive `'x`
error[E0502]: cannot borrow `*b_ref` as mutable because it is also borrowed as immutable
--> <source>:51:9
|
38 | impl<'x> C<'x>{
| -- lifetime `'x` defined here
...
50 | a_ref.push_b(b_ref);
| -------------------
| | |
| | immutable borrow occurs here
| argument requires that `*b_ref` is borrowed for `'x`
51 | b_ref.push_a(a_ref);
| ^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
error: aborting due to 2 previous errors
I try to do it but I'm stuck. How can i do a simple thing like this without dynamic memory allocation like Rc, Arc, etc....?