How can I return a reference wrapped in a struct and what lifetime annotation is required? I am having a tough time formulating my exact question, but the following example illustrates what I am trying to do. I have a struct C
that contains a reference to a struct B
that requires lifetime parameters. I want a function on C
that returns the reference to B
wrapped in another struct Borrower
that functions as an interface.
When compiling this I get an error when returning Borrower
: 'cannot infer an appropriate lifetime for lifetime parameter 'b
due to conflicting requirements'. How can I resolve this issue? What lifetime parameters can I enter? I feel like both 'a
and 'b
are not the right lifetimes.
struct C<'a, 'b> {
ref2: &'a mut B<'b>,
}
impl<'a, 'b> C<'a, 'b> {
fn get_borrower(&mut self) -> Borrower {
Borrower { ref3: self.ref2 }
}
}
struct Borrower<'a, 'b> {
ref3: &'a mut B<'b>,
}
impl<'a, 'b> Borrower<'a, 'b> {
fn print_and_add(&mut self) {
println!("ref is {}", self.ref3.ref1.i);
self.ref3.ref1.i += 1;
}
}
struct B<'a> {
ref1: &'a mut A,
}
struct A {
i: u32,
}
fn main() {
let mut a = A { i: 10 };
let mut b = B { ref1: &mut a };
let mut c = C { ref2: &mut b };
for _ in 0..10 {
let mut borrower = c.get_borrower();
borrower.print_and_add();
}
}