0

I have issue with lifetimes and references. I have three structs:

struct Foo<'a> {
    bar: Bar,
    lar: Lar<'a>
}
   
struct Bar;
    
struct Lar<'a> {
    bar: &'a Bar
}

I want to create the final structure like this:

Foo {
    bar: Bar::new(),
    lar: Lar::new(&bar); // use the reference to bar created above
}

I tried two approaches: 1.

fn main() {
    let bar = Bar::new();
    Foo {
        bar,
        lar: Lar::new(&bar) // at this point the scope of bar is still just the function block, 
        // I get: returns a value referencing data owned by the current function
    }
}
fn main() {
    let mut foo = Foo {
        bar: Bar::new(),
        ..Default::default() // even if I use @[derive(Default)] on all the structs, 
        //I still get: the trait `std::default::Default` is not implemented for `&Bar`, 
        //I think the problem is that its a referrence not the actuall structure
    };
    foo.lar = Lar::new(&foo.bar);
    foo
}

How would I solve this? Thank you

stove
  • 556
  • 6
  • 24
  • 2
    This is a well-known problem in rust, called the "self-referencing struct" problem. It usually means you have either a design issue or too many levels of indirection. There's no way to fix this as is without unsafe and pin. There are libraries that tried to solve this problem, but some of them had soundness issues. I'd recommend you find another way. – The Quantum Physicist Mar 03 '23 at 13:32
  • @TheQuantumPhysicist I see, thank you for explaining. Originally I wanted to make Bar a singleton, but I had read that it is a bad practice and I should rather be handing it through as a reference... – stove Mar 03 '23 at 13:40

0 Answers0