this post was submitted on 15 Mar 2025
21 points (95.7% liked)
Rust
6697 readers
102 users here now
Welcome to the Rust community! This is a place to discuss about the Rust programming language.
Wormhole
Credits
- The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)
founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
One way of solving this is to structure all of your nodes into a HashMap with the node ID as the key and the node type as the value. The underlying node type could have node IDs for referencing purposes. You lose the ability to reference the parent/child/sibling directly, but you avoid direct circular dependencies. That said, now you need to manage dangling references for when the node is removed from the main HashMap collection.
Thanks, this sounds like a pretty serious abstraction inversion, exposes you to various kinds of bugs such as memory leaks, and gives a performance hit from all the hashing compared with using machine pointers, but I guess it does get rid of the circular references. Is it really the idiomatic answer? I'm ok if it is, but it's not what I'd have expected from a low level language designed to replace C.
There are a few different ways to solve this problem without using unsafe and I'm not sure what would be considered idiomatic. Another option is to ultimately encapsulate all of the nodes in a reference-counted box like Rc or Arc and specify the type of your parent/child/sibling references to the same reference-counted box type. With that, you just share cloned instances around as needed.
The primary drawback here is that for mutable access you end up having to perform a lock every time on an underlying Mutex (or something similar). You also no longer have direct access to the singular instance of the node.
There are pros and cons to every approach.
Thanks. I might ask on irc how Servo does it. Given Servo's connection with Rust, it would be surprising for this to be too awkward.
Sounds good. Please share what you find and what you end up going with.
I'm not trying to code anything right now. I'm just trying to understand Rust itself better, so I asked how its users deal with a particular problem. Thanks!