Follow

Finished challenge 6 today and had to fight with the borrow checker a lot.

Everything worked in the end, but sharing mutable references in rust is quite a messy thing. Now my type definition looks like

Option<Rc<RefCell<Orbit>>>

And my code is full of

orbit.borrow().parent.as_ref().unwrap().clone();

I wonder if there is a cleaner way 🤔...

@dnaka91 yeah. You can alias your type `pub type SharableOrbit = Rc<RefCell<Orbit>>` or even better create a wrapping type `struct SharableOrbit(Rc<RefCell<Orbit>>)` that provides convenience functions that return an appropriate `Result<_>` when get()ing the internals and then use that with the `?` operator.

Results in way less messy code.

@musicmatze Thanks for the tips. A type alias doesn't help much with the function calls, but it's a great idea to wrap it in a tuple struct for easier function calls.

Actually just came up with an idea to make it work with just a simple HashMap and not creating all the links between structs. Have to try that later.

Anyways thanks. I will keep that in mind next time I some Rc + RefCell constructs.

@dnaka91 A cleaner way is to avoid mutable references =)

Sign in to participate in the conversation
Mastodon for Tech Folks

The social network of the future: No ads, no corporate surveillance, ethical design, and decentralization! Own your data with Mastodon!