by simonask · 7mo ago · 0 comments
Internally shared ownership is a huge anti-pattern and rarely achieves what you’re actually trying to do. Graphs like these are much better represented by splitting the topology from the node data, and using indices or keys to form edges instead of (smart) pointers.
You can use pointers, but then the correct choice is actually raw pointers and `unsafe`, with a safe whole-graph-level API for traversal and access. This is what Rust’s own collection types do internally.
I always heard that but comming from Python internal references would be the way to go so it's not natural to me.
Node data in one list. Indices of node parents in another list of the same length. If you need to find children quickly, you can have another list of lists containing children indices.
The key is to consider the node’s position in the list as its ID, and refer to nodes by that index instead of the pointer.
In most cases, this model is both easier to work with and more performant. For example, you can usually get by with 32-bit indices instead of 64-bit pointers, so things are much more likely to be in cache.
Edit: also the simplest way how to do cyclic structures is to heap-allocate via Box and leak memory. Box::leak This is also mentioned in the linked article.