When a Rust graph editor keeps fighting the borrow checker, how do you decide whether to restructure around indices or an arena rather than patch with `clone()` or `RefCell`?
answer
- who owns each node?
- references describe trees, not graphs
- a Copy id borrows nothing
- stale index instead of dangling pointer
- patch locally, restructure globally
basics
~20 sPatch a local conflict: reorder, narrow a borrow, copy a small value. Restructure when the data is a graph references cannot express: one Vec of nodes linked by Copy ids removes the conflicts but loses compile-time checks on stale ids.
solid answer
~50 sFirst ask whether the error is local or structural. A local conflict, a borrow kept a few lines too long or a field moved out of `&mut self`, has a local fix: reorder, copy out a small value, use `mem::take`. A structural conflict shows up as the same error in many places: nodes that point at each other, passes that walk and edit at once, lifetimes spreading through every type. That usually means a graph is being expressed with references, which describe ownership trees. The usual restructure keeps one owner, `Vec<Node>`, and links nodes by a `Copy` index such as `struct NodeId(usize)`; cycles and walk-while-editing become ordinary code. The price: the compiler no longer checks that an id is still valid, so deleting nodes needs a free list or generation counters. `clone()` is fine for small values but splits state, and `Rc<RefCell<_>>` moves the borrow check to run time; reserve both for genuinely shared ownership.
code
rust · 34 lines#[derive(Clone, Copy, Debug)]
struct NodeId(usize);
struct Node { label: String, edges: Vec<NodeId> }
#[derive(Default)]
struct Graph { nodes: Vec<Node> } // the single owner of every node
impl Graph {
fn add(&mut self, label: &str) -> NodeId {
self.nodes.push(Node { label: label.to_string(), edges: Vec::new() });
NodeId(self.nodes.len() - 1)
}
fn connect(&mut self, from: NodeId, to: NodeId) { self.nodes[from.0].edges.push(to); }
// Walk and grow the graph at once: we hold Copy ids, not references.
fn add_leaf_children(&mut self) {
for i in 0..self.nodes.len() {
if self.nodes[i].edges.is_empty() {
let child = self.add(&format!("{}-child", self.nodes[i].label));
self.connect(NodeId(i), child);
}
}
}
}
fn main() {
let mut g = Graph::default();
let (a, b) = (g.add("a"), g.add("b"));
g.connect(a, b);
g.connect(b, a); // a cycle, with no lifetimes, Rc or RefCell
g.add("c");
g.add_leaf_children();
for n in &g.nodes { println!("{} -> {:?}", n.label, n.edges); }
}go deeper
Recall the standard local fixes, reordering, copying out a small value and index loops, before reaching for clone or RefCell.
Explain why references model ownership trees and why a graph with cycles or edit-while-walk passes does not fit them.
Recognise the repeated-error pattern that signals a structural problem and implement a Vec-plus-NodeId arena, including how deletion is handled.
Own the tradeoff: compile-time checks on references versus runtime discipline on ids and RefCell, and set a team rule for when a patch must become a redesign.
## Local errors and structural errors Most borrow-checker errors are **local**. A reference lives a few lines too long, a loop holds a borrow across a push, a method tries to move a field out of `&mut self`. The fix is in the same function: reorder, copy out a value, use an index loop, use `mem::take`. A lead's job is to tell those apart from **structural** errors, where the code is asking the borrow checker to verify a shape it was not built to verify. Signs the problem is the design, not the line: - the same E0499 or E0502 returns in every new feature that touches the data; - structs gain lifetime parameters that then spread through every type that holds them; - nodes need to refer to each other, including cycles and parent links; - passes need to walk the structure and edit it at once; - review comments keep asking why this `clone()` or this `RefCell` is here. ## Why references fit trees, not graphs A `&T` or `&mut T` is a **borrow from an owner**, checked against that owner's scope. Ownership in Rust forms a tree: each value has one owner. A graph with cycles has no such tree. A design that stores `&Node` inside `Node` needs every node to outlive the others, which in practice forces an external arena plus interior mutability, and one that stores `&mut` links breaks the one-mutable-borrow rule by construction. ## The patches and what they cost | Patch | What it buys | What it costs | |---|---|---| | Reorder or narrow a borrow | the error goes away at zero cost | nothing, when the conflict really is local | | `clone()` a small value | no borrow to conflict | a copy, and two values that can drift apart | | `clone()` a collection to iterate | mutation of the original during the walk | an allocation and a copy per pass | | `Rc<RefCell<Node>>` | shared, mutable nodes with cycles | runtime borrow checks that panic on conflict, reference cycles that leak without `Weak`, and no `Send` | | `unsafe` raw pointers | any shape | the guarantees the borrow checker was giving you | `Rc` and `RefCell` are the material on smart pointers; here the point is only that they move the check from compile time to run time. ## The restructure: one owner, typed indices Put every node in one container that owns them all, and link nodes by a small `Copy` handle: - `struct Graph { nodes: Vec<Node> }` is the single owner; - `#[derive(Clone, Copy)] struct NodeId(usize);` is the link, and it borrows nothing; - methods take `&mut self` on the graph and look nodes up by id when they need them. Cycles become two `push` calls. Walking and growing the graph in one pass becomes an index loop, because holding a `NodeId` across `self.add(..)` creates no borrow. A newtype rather than a bare `usize` stops ids from different containers being mixed by accident. ## What the arena gives up - **Stale ids.** After a node is removed, an old `NodeId` can point at nothing or at a reused slot. The compiler cannot catch this; a generation counter stored with each slot and checked on lookup can. - **Panics instead of compile errors.** `self.nodes[id.0]` panics on an out-of-range id; `get` returns an `Option` if you want to handle it. - **Aliasing per node is coarser.** You borrow the whole graph mutably to edit one node, so two simultaneous `&mut` nodes need a split such as `split_at_mut`, covered with slices. ## A decision procedure 1. **Is the error local?** Reorder, narrow, copy a small value, or use `mem::take`. Stop here most of the time. 2. **Is the shape a tree?** Use plain ownership: parents own children in `Vec<Node>` or `Box`, and pass references down. 3. **Is the shape a graph, or do passes edit while walking?** Restructure around one owner and `Copy` ids. Add generations if nodes are deleted. 4. **Is ownership genuinely shared**, with lifetimes no single owner can describe? Then shared-ownership types are the honest model, behind a small API so the runtime checks stay contained. ## A team rule worth writing down A `clone()` or a `RefCell` added only to silence the borrow checker needs a reason in the pull request. Two patches for the same data structure in one quarter is the trigger to discuss restructuring it, because the third will come.
- How do you stop a deleted node's old `NodeId` from silently reaching a new node that reused its slot?Store a generation counter in each slot and in each id. Removing a node bumps the slot's generation; lookup compares the two and returns `None` on a mismatch. The bug becomes a handled `None` instead of reading the wrong node.
- When is `Rc<RefCell<Node>>` the right call despite its costs?When ownership is genuinely shared and no single container can own the nodes, for example values handed to independent subsystems with unrelated lifetimes, on one thread. Keep it behind a small API so `borrow_mut` calls cannot overlap, and use `Weak` for back-links.
- Every borrow error means the design is wrong and needs a rewrite.
- Rc<RefCell<T>> is free: it just turns the borrow checker off.
- Indices into a Vec are unsafe because they bypass the borrow checker.
- Cloning to silence a borrow error is never acceptable in review.
- An arena with plain usize indices catches use of a deleted node at compile time.