I have these (minimal, hence convoluted) structs:
#[derive(Debug)]
struct A(u32);
impl A {
fn new() -> A{
A(42)
}
}
#[derive(Debug)]
struct B<'a>(&'a mut A);
I want to return a B
from a function. However, B
needs a reference to a new, unique A
. My idea was to make the A
in the same place, then shove them both inside a thing to keep them together:
use core::pin::Pin;
struct Thing<'a> {
pub b: B<'a>,
a_box: Pin<Box<A>>
}
fn get_thing() -> Thing<'static> {
let mut a = Pin::new(Box::new(A::new()));
Thing {
b: B(&mut a),
a_box: a
}
}
fn main() {
let x = get_thing();
println!("{:?}", x.b);
}
However, this doesn't compile:
Compiling playground v0.0.1 (/playground) error[E0515]: cannot return value referencing local variable `a` --> src/main.rs:22:5 | 22 | / Thing { 23 | | b: B(&mut a), | | ------ `a` is borrowed here 24 | | a_box: a 25 | | } | |_____^ returns a value referencing data owned by the current function error[E0505]: cannot move out of `a` because it is borrowed --> src/main.rs:24:16 | 22 | / Thing { 23 | | b: B(&mut a), | | ------ borrow of `a` occurs here 24 | | a_box: a | | ^ move out of `a` occurs here 25 | | } | |_____- returning this value requires that `a` is borrowed for `'static` error: aborting due to 2 previous errors
How do I tell the compiler that I am, in fact, preserving the relationship between these two structs? Is there a good way, or should I resort to unsafe
code?