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.

Sign in to participate in the conversation
Mastodon for Tech Folks

This Mastodon instance is for people interested in technology. Discussions aren't limited to technology, because tech folks shouldn't be limited to technology either!