[Solved] Creating object with shared reference to parent

Hello, I'm trying to achieve the following pattern:

The problem is that if I use RefCell I get errors of moving out of borrowed content or mismatched types, and if I use RefCell<&Database> I get (almost) impossible to fix lifetimes. So, is there an easier solution for a pattern like this?

Thanks in advance!

The way I deal with this is to have Database in this case have a handle/id that the user can hold on to like

#[derive(PartialEq, Clone, Copy)]
pub struct DatabaseHandle(pub u64);

Then later when some code needs to know which database the user is in the handle is used to find the correct one. I'm not sure if there is some better way to do this but that is one way that works at least.

This could also be solved using Rc. You could, for example, let Database be a wrapper around it to expose a more convenient interface: Rust Playground

1 Like

Wow! that really makes sense! I'll use that version, thanks!

@emoon, I think I understand your version, but I think this way I can do it more understandable for reading the code. Thanks though! :slight_smile:

Oh, and I almost forgot that you don't necessarily need to take &mut self in the Database methods if you are using RefCell internally. You can still do it, though, if you want to keep the borrow-once-restriction.

1 Like