0

I am developing a personal project using Rust, but currently I am having troubles to create and return an object in which one of the members has a reference its parent / container.

Here is a simplified version of the code :

struct Parent<'a> {
    child: Option<Child<'a>>,
}

struct Child<'a> {
    parent: &'a Parent<'a>,
}

fn get_object<'a>() -> Parent<'a> {
    let mut object = Parent {
        child: None,
    };

    object.child = Some(Child {
        parent: &object,
    });

    return object;
}

I tried different tweaks to make this code compile, changing the code structure and lifetimes but ultimately it did not work, and I get different error messages depending on how I try it.

I would really appreciate some help with this, thank you for reading.

  • I just read this and I now understand why I cannot return `object` in my code yes. However, I still do not get why I cannot assign `Some( Child { parent: &object });` to `object.child`, the error is quite explicit (cannot assign to `object.child` because it is borrowed), but I would like to know if there is a way to get around. – Maxime Mulder Jan 24 '20 at 04:00
  • [Also…](https://rust-unofficial.github.io/too-many-lists/) – Jmb Jan 24 '20 at 07:11

0 Answers0