1

I want to create a struct which referecnces to it self like following:

struct Item<'a> {
    id: String,
    children: Vec<&'a mut Item<'a>>,
    parents: Vec<&'a mut Item<'a>>
}

At the moment I use a hashmap for all Items and save the id: String in the children/parents vectors. I am curious how I can improve the performance and usablility by avoiding the hashmap lookup for all my related ids with references. It is working with unmutable borrowed references, but then I loose the advantage to add or remove children/parents from related Items. Because one Item can be linked to multiple other Items, I would need multiple mutable references which is prohibited. Is it possible with Rc and RefCell?

How do I design a datatype like this correctly or is it nonsense?

  • 2
    I don't think two structs can [hold direct mutable references to each other](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021)? – Jared Smith Feb 24 '23 at 18:23
  • The link only shows a hello world program? – Julius Athenstaedt Feb 24 '23 at 19:13
  • Aargh sorry everybody thought I had and of course when I clicked the link it showed my code because it saves it in localStorage. Here's the fixed link https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7cf2d56eab2f3d2ad1e44f8cbd5fd19a – Jared Smith Feb 24 '23 at 19:41

1 Answers1

2

You can't use references because you would have 2 ways of obtaining the same mutable reference one is &mut self the other is along self.children[x].parents[y] where parent[y] of child[x] is self but mutable references have to be exclusive. And yes you can use interior mutability using Cell, RefCell, Mutex or RwLock depending on your usecase instead. Additionally add Rc or Arc (or the respective Weak for the parents) for the shared ownership.

If performance is critical you might have to go the way stds LinkedList went and use unsafe with raw pointers instead.

cafce25
  • 15,907
  • 4
  • 25
  • 31