1

The following code creates a struct holding a reference to a struct which is moved out of the function at the end. The borrow checker gets angry because, I suppose, moving something kills it's original location. My question is: without changing the definitions of the structs, is it possible for me to construct a B and an A referencing that B inside another function, and then return them to the calling context?

#[derive(Debug)]
pub struct A<'a> {
    pub b: &'a B,
}

impl<'a> A<'a> {
    pub fn new(b: &'a B) -> A<'a> {
        A { b }
    }
}

#[derive(Debug)]
pub struct B {
    pub x: i32,
}

fn nested<'a>() -> (A<'a>, B) {
    let x = 0;
    let b = B { x };
    let a = A::new(&b);
    (a, b)
}

fn main() {
    let (a, b) = nested();
    println!("{:?}", a);
}
FizzixNerd
  • 609
  • 1
  • 5
  • 9
  • 2
    The very similar question https://stackoverflow.com/questions/50891977/can-i-return-a-value-and-a-reference-to-it-from-a-function was marked as a duplicate of https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct (the answer is no, returning the value from a function doesn't grant a reference to its future location). Does this answer your question? – trent Jul 23 '18 at 16:57
  • @trentcl perfect. Sorry for the duplicate. – FizzixNerd Jul 23 '18 at 17:18

0 Answers0