[rust-dev] What do I do if I need several &muts into a struct?

Niko Matsakis niko at alum.mit.edu
Fri Jun 20 02:37:09 PDT 2014


On Mon, Jun 16, 2014 at 09:59:45PM +0100, Vladimir Pouzanov wrote:
> Everything works fine up to the point of references. References allow some
> nodes to modify other nodes. So, the first pass — I parse that snippet into
> PlatformTree/Nodes struct. Second pass — I walk over the tree and for each
> reference I invoke some handling code, e.g. in the handler of thread node
> it might add some attribute to lpx17xx node. Which is not really possible
> as it's in immutable Gc box. Also, such modifications are performed through
> `named` hashmap, so I can't even store &muts in `nodes`, as I still can
> store only immutable pointers in `named`.
> 
> How would you solve this problem?

I would either:

1. Use RefCell or Cell for the fields that need to be modified. No
shame in that.

2. Not use GC/RC etc but instead use a Vector that holds all the
nodes. Use newtyped indices to represent pointers. Convert your nodes
vec, therefore, to `HashMap<String, NodeIndex>` and so on. This allows
you to freeze and unfreeze the whole graph at once.

The second option is appropriate if your set of nodes only grows.
Once you start removing nodes it becomes less attractive, because your
index set becomes non-dense and you start writing free lists (though
that might be a useful library at some point).

Certainly, due to Rust's emphasis on ownership, graphs can be the
hardest thing to represent. The best answer will depend on the
particulars of your situation: what access patterns you need, what
lifetimes the nodes have, and so forth.

Let me know if you want more details.



Niko


More information about the Rust-dev mailing list