rust-unofficial / patterns

A catalogue of Rust design patterns, anti-patterns and idioms
https://rust-unofficial.github.io/patterns/
Mozilla Public License 2.0
7.87k stars 357 forks source link

Circular references (bidirectional linked lists, etc) #197

Open vchekan opened 3 years ago

vchekan commented 3 years ago

Cyclic references in Rust are impossible in straightforward way and workarounds are required.

  1. Describe reason why it is so.
  2. Show different examples when cyclic reffereneces are present
  3. Describe solutions (Rc, Vec with storing indexes, Slotmap)

While problem with linked list is simple to grasp, sometimes when the proble manifest itself on architecture level, it is more difficult to realize that you are dealing with cyclic references. Perhaps this presentation can be an example for architecture that can benefit: https://www.youtube.com/watch?v=P9u8x13W7UE

Relevant reddit thread: https://www.reddit.com/r/rust/comments/kq6lt2/slotmap_10_has_been_released_copy_restriction/

MarcoIeni commented 3 years ago

Should this be an idiom?

pickfire commented 3 years ago

I don't think it is an idiom, it is sort of a pattern. Usually when circular links are involved, it is better to have reference to another storage, but beginners don't know that (like when I get started). Other options includes using a bump allocator or even plain Vec. When creating games, one would most likely hit this.