1

How can I make a child struct have a reference to one of it's parents fields?

Example:

pub struct Parent<'a> {
    s: String,
    child: Child<'a>,
}

pub struct Child<'a> {
    s: &'a String,
}

How do I get Child.s to point to Parent.s without triggering the borrow checker?

let s = String::new();

let child = Child {
    s: &s
};

let parent = Parent {
    child,
    s,
};

This code triggers the following error since it's borrowed by child when trying to move to parent:

cannot move out of 's' because it is borrowed

Any pointers appreciated

Mendy
  • 7,612
  • 5
  • 28
  • 42

1 Answers1

1

Easiest way is to use some kind of smart pointer, Rc would do:

use std::rc::Rc;

pub struct Parent {
    s: Rc<String>,
    child: Child,
}

pub struct Child {
    s: Rc<String>,
}

fn main() {
    let s = Rc::new(String::new());

    let child = Child { s: s.clone() };

    let parent = Parent { child, s };
}

Playground

In case it also needs to be mutable, check the docs on Sharable mutable containers

Netwave
  • 40,134
  • 6
  • 50
  • 93
  • I need it to be editable, I know that I can use `RefCell` for that but then I lose some borrow checking – Mendy Apr 29 '22 at 15:49
  • @Mendy, `Rc` then. It is well explained in the [docst](https://doc.rust-lang.org/std/cell/index.html) – Netwave Apr 29 '22 at 15:52
  • As I mentioned in my previous comment I know about that, but I don't wanna loose compile time borrow checking – Mendy Apr 29 '22 at 15:55
  • @Mendy, yeah, I understand. But that is the way it is :( Otherwise you will have to deal with raw pointers and `unsafe` terrain. Even more when dealing with mutable stuff. – Netwave Apr 29 '22 at 15:57