0

I want to reference a member of the struct inside the struct but I can't get it to work without Rc. But I'm not understanding why it doesn't work in the first place.

My understanding is that new_value is moved to self.value and the self.ref_value is guaranteed to live as long as self.value. (Compilation errors in code)

Clearly, I'm wrong so if someone could explain to me this problem and suggest the best solution to deal with this, I would appreciate it.

struct Foo<'a> {
    value: Bar,
    ref_value: &'a Bar
}

struct Bar {
    x: i32
}

impl<'a> Foo<'a> {
    fn new() -> Self {
        let new_value = Bar{ x: 1 };
        Self {
            ref_value: &new_value, // cannot return value referencing local variable `new_value`
            value: new_value,      // cannot move out of `new_value` because it is borrowed
        }
    }
}

I also tried switching the initialization order but to no surprise it's a borrow after move. Wrapping the value with Rc works but looks ugly.

Keep in mind I'm new to Rust and I want a deeper understanding of the language.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
tcerqueira
  • 21
  • 2

0 Answers0