Say a B
contains a reference to an A
:
struct A;
struct B<'t> {
a_ref: &'t A,
}
My goal is to write a simple function f
that makes the following two equivalent (though one may use the heap).
let (a, b) = f();
let a = A { };
let b = B { a_ref: &a };
How would I write f
? Here's an attempt:
fn f<'t>() -> (A, B<'t>) {
let a = A { };
let b = B { a_ref: &a };
(a, b)
}
But it fails to compile with two errors, which I understand but am not sure how to avoid:
error[E0515]: cannot return value referencing local variable `a`
error[E0505]: cannot move out of `a` because it is borrowed
I have seen Why can't I store a value and a reference to that value in the same struct?. Above, I wrote two lines of code that create an A
and a B
. My question is not why my attempt to abstract those two lines fails. My question is how to abstract (something like) those two lines.
Yes, my attempt tries to store a value and a reference to that value in a struct, but whatever, that is not the goal. I know that does not and cannot work. That is not what I'm trying to accomplish. My goal is something unrelated and which may be possible regardless. For example, returning a closure or using a macro could work.