[Solved] Creating object with shared reference to parent


#1

Hello, I’m trying to achieve the following pattern:
https://play.rust-lang.org/?gist=ae35f7d1f20de67398c54604bf8eda03&version=stable&backtrace=0

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!


#2

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.


#3

This could also be solved using Rc. You could, for example, let Database be a wrapper around it to expose a more convenient interface: http://is.gd/B2vgbG


#4

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:


#5

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.