medium.com 7 min read Original Source

I Tried to Build a Graph in Rust. Rc and RefCell Were Waiting for Me.

Part of the Data Structures in Rust series.

A dependency manager is a graph. Package A depends on B, B depends on C, and a circular dependency creates a cycle the package manager has to detect and reject. A routing table is also a graph: each location stores connections to neighbouring locations, and finding the shortest path means traversing those connections efficiently. The data structure underlying both is the same, and implementing it in Rust exposes something worth understanding about how ownership shapes design decisions.

Pointer-based linked lists are one of the worst fits for Rust’s ownership model because they require nodes to hold mutable links in both directions. Graphs have the same problem, amplified. A graph node can have any number of edges pointing to any other node, including back to itself. There is no hierarchy, no single direction of ownership, no clean parent-child relationship the compiler can reason about statically. Node A might point to Node B, which points to Node C, which points back to Node A.

Expressing this in Rust forces a choice: reach for Rc<RefCell<T>> and accept runtime borrow checking, or change the representation entirely and use integer indices into a Vec. The first works for limited cases. The second is how production Rust graph code actually works, and understanding why requires first seeing what goes wrong with the pointer approach.

The Rc<RefCell> approach and what it costs you

A graph node needs to hold edges to other nodes. Since multiple nodes can share ownership of a single node (A points to B and C also points to B), Box<T> is off the table: it enforces single ownership. Rc<T> solves the sharing problem by keeping a reference count and dropping the allocation when that count reaches zero.

The problem is that graph edges are usually relationships, not ownership relationships. Rc treats every edge as ownership, which is why cycles become memory leaks. After all external references disappear, each node in a cycle still owns the other through its edge list, leaving both reference counts above zero. Neither allocation ever gets cleaned up. Rc is reference counting only, not a cycle-detecting garbage collector.

Rc<T> is also immutable by default. Mutating the value inside an Rc through a shared reference requires RefCell<T>, which moves the borrow check from compile time to runtime and panics if you violate it.

<button data-code="use std::rc::Rc;
use std::cell::RefCell;

type NodeRef = Rc<RefCell>;
#[derive(Debug)]
struct Node {
value: i32,
edges: Vec,
}
impl Node {
fn new(value: i32) -> NodeRef {
Rc::new(RefCell::new(Node {
value,
edges: Vec::new(),
}))
}
}
struct Graph {
nodes: Vec,
}
impl Graph {
fn new() -> Self {
Graph { nodes: Vec::new() }
}
fn add_node(&mut self, value: i32) -> NodeRef {
let node = Node::new(value);
self.nodes.push(Rc::clone(&node));
node
}
fn add_edge(&self, from: &NodeRef, to: &NodeRef) {
from.borrow_mut().edges.push(Rc::clone(to));
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use std::rc::Rc;
use std::cell::RefCell;

type NodeRef = Rc<RefCell<Node>>;
#[derive(Debug)]
struct Node {
    value: i32,
    edges: Vec<NodeRef>,
}
impl Node {
    fn new(value: i32) -> NodeRef {
        Rc::new(RefCell::new(Node {
            value,
            edges: Vec::new(),
        }))
    }
}
struct Graph {
    nodes: Vec<NodeRef>,
}
impl Graph {
    fn new() -> Self {
        Graph { nodes: Vec::new() }
    }
    fn add_node(&mut self, value: i32) -> NodeRef {
        let node = Node::new(value);
        self.nodes.push(Rc::clone(&node));
        node
    }
    fn add_edge(&self, from: &NodeRef, to: &NodeRef) {
        from.borrow_mut().edges.push(Rc::clone(to));
    }
}
use std::rc::Rc;
use std::cell::RefCell;

type NodeRef = Rc<RefCell<Node>>;
#[derive(Debug)]
struct Node {
    value: i32,
    edges: Vec<NodeRef>,
}
impl Node {
    fn new(value: i32) -> NodeRef {
        Rc::new(RefCell::new(Node {
            value,
            edges: Vec::new(),
        }))
    }
}
struct Graph {
    nodes: Vec<NodeRef>,
}
impl Graph {
    fn new() -> Self {
        Graph { nodes: Vec::new() }
    }
    fn add_node(&mut self, value: i32) -> NodeRef {
        let node = Node::new(value);
        self.nodes.push(Rc::clone(&node));
        node
    }
    fn add_edge(&self, from: &NodeRef, to: &NodeRef) {
        from.borrow_mut().edges.push(Rc::clone(to));
    }
}

The memory leak from a cycle:

fn main() {
    let mut graph = Graph::new();
    let a = graph.add_node(1);
    let b = graph.add_node(2);

graph.add_edge(&a, &b);
    graph.add_edge(&b, &a); // cycle
    // After graph and locals drop, each node still owns the other
    // through its edge list. Both reference counts stay above zero.
    // Neither allocation is freed. Memory leak.
}
fn main() {
    let mut graph = Graph::new();
    let a = graph.add_node(1);
    let b = graph.add_node(2);

graph.add_edge(&a, &b);
    graph.add_edge(&b, &a); // cycle
    // After graph and locals drop, each node still owns the other
    // through its edge list. Both reference counts stay above zero.
    // Neither allocation is freed. Memory leak.
}

Weak<T> can break cycles in hierarchical structures where parent-child relationships are clear, such as a tree where children weakly reference their parent:

<button data-code="struct Node {
parent: std::rc::Weak,
children: Vec<Rc>,
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

struct Node {
    parent: std::rc::Weak<Node>,
    children: Vec<Rc<Node>>,
}
struct Node {
    parent: std::rc::Weak<Node>,
    children: Vec<Rc<Node>>,
}

For arbitrary graph structures with edges in any direction, Weak does not generalise. The right answer is to stop treating edges as ownership.

The index-based graph

A graph node does not need to hold pointers to its neighbors. It can hold indices into an array where the neighbors live. The Graph struct owns all the nodes in a Vec. Each node stores a list of indices, not references. No ownership conflicts, no reference counting, no runtime borrow checking, no cycles that the allocator cannot handle.

<button data-code="#[derive(Debug)]
struct Node {
value: i32,
edges: Vec, // indices into Graph.nodes
}

struct Graph {
nodes: Vec,
}
impl Graph {
fn new() -> Self {
Graph { nodes: Vec::new() }
}
fn with_capacity(capacity: usize) -> Self {
Graph { nodes: Vec::with_capacity(capacity) }
}
fn add_node(&mut self, value: i32) -> usize {
let index = self.nodes.len();
self.nodes.push(Node { value, edges: Vec::new() });
index
}
fn add_edge(&mut self, from: usize, to: usize) {
self.nodes[from].edges.push(to);
}
fn add_undirected_edge(&mut self, a: usize, b: usize) {
self.nodes[a].edges.push(b);
self.nodes[b].edges.push(a);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

#[derive(Debug)]
struct Node {
    value: i32,
    edges: Vec<usize>, // indices into Graph.nodes
}

struct Graph {
    nodes: Vec<Node>,
}
impl Graph {
    fn new() -> Self {
        Graph { nodes: Vec::new() }
    }
    fn with_capacity(capacity: usize) -> Self {
        Graph { nodes: Vec::with_capacity(capacity) }
    }
    fn add_node(&mut self, value: i32) -> usize {
        let index = self.nodes.len();
        self.nodes.push(Node { value, edges: Vec::new() });
        index
    }
    fn add_edge(&mut self, from: usize, to: usize) {
        self.nodes[from].edges.push(to);
    }
    fn add_undirected_edge(&mut self, a: usize, b: usize) {
        self.nodes[a].edges.push(b);
        self.nodes[b].edges.push(a);
    }
}
#[derive(Debug)]
struct Node {
    value: i32,
    edges: Vec<usize>, // indices into Graph.nodes
}

struct Graph {
    nodes: Vec<Node>,
}
impl Graph {
    fn new() -> Self {
        Graph { nodes: Vec::new() }
    }
    fn with_capacity(capacity: usize) -> Self {
        Graph { nodes: Vec::with_capacity(capacity) }
    }
    fn add_node(&mut self, value: i32) -> usize {
        let index = self.nodes.len();
        self.nodes.push(Node { value, edges: Vec::new() });
        index
    }
    fn add_edge(&mut self, from: usize, to: usize) {
        self.nodes[from].edges.push(to);
    }
    fn add_undirected_edge(&mut self, a: usize, b: usize) {
        self.nodes[a].edges.push(b);
        self.nodes[b].edges.push(a);
    }
}

For large graphs built incrementally, with_capacity avoids repeated reallocations during construction. Vec growth does not affect stored indices because they refer to logical positions rather than memory addresses. However, removing or moving elements can invalidate them, which the production section at the end addresses.

Building a graph with a cycle causes no memory management problem:

<button data-code="fn main() {
let mut graph = Graph::new();

let a = graph.add_node(1); // 0
let b = graph.add_node(2); // 1
let c = graph.add_node(3); // 2
let d = graph.add_node(4); // 3
graph.add_edge(a, b);
graph.add_edge(a, c);
graph.add_edge(b, d);
graph.add_edge(c, d);
graph.add_edge(d, a); // cycle: just the integer 0 stored in a Vec
// When graph drops, Vec drops, everything cleans up.
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn main() {
    let mut graph = Graph::new();

let a = graph.add_node(1); // 0
    let b = graph.add_node(2); // 1
    let c = graph.add_node(3); // 2
    let d = graph.add_node(4); // 3
    graph.add_edge(a, b);
    graph.add_edge(a, c);
    graph.add_edge(b, d);
    graph.add_edge(c, d);
    graph.add_edge(d, a); // cycle: just the integer 0 stored in a Vec
    // When graph drops, Vec<Node> drops, everything cleans up.
}
fn main() {
    let mut graph = Graph::new();

let a = graph.add_node(1); // 0
    let b = graph.add_node(2); // 1
    let c = graph.add_node(3); // 2
    let d = graph.add_node(4); // 3
    graph.add_edge(a, b);
    graph.add_edge(a, c);
    graph.add_edge(b, d);
    graph.add_edge(c, d);
    graph.add_edge(d, a); // cycle: just the integer 0 stored in a Vec
    // When graph drops, Vec<Node> drops, everything cleans up.
}

Breadth-first search

BFS visits every node reachable from a starting node, in order of increasing distance from the start. A Vec<bool> indexed by node index avoids hashing overhead and provides compact storage, which is preferable here because node identifiers are already dense integers.

Vec {
let mut visited = vec![false; self.nodes.len()];
let mut queue = VecDeque::new();
let mut result = Vec::new();
visited[start] = true;
queue.push_back(start);
while let Some(index) = queue.pop_front() {
result.push(self.nodes[index].value);
for &neighbor in &self.nodes[index].edges {
if !visited[neighbor] {
visited[neighbor] = true;
queue.push_back(neighbor);
}
}
}
result
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

use std::collections::VecDeque;

impl Graph {
    fn bfs(&self, start: usize) -> Vec<i32> {
        let mut visited = vec![false; self.nodes.len()];
        let mut queue = VecDeque::new();
        let mut result = Vec::new();
        visited[start] = true;
        queue.push_back(start);
        while let Some(index) = queue.pop_front() {
            result.push(self.nodes[index].value);
            for &neighbor in &self.nodes[index].edges {
                if !visited[neighbor] {
                    visited[neighbor] = true;
                    queue.push_back(neighbor);
                }
            }
        }
        result
    }
}
use std::collections::VecDeque;

impl Graph {
    fn bfs(&self, start: usize) -> Vec<i32> {
        let mut visited = vec![false; self.nodes.len()];
        let mut queue = VecDeque::new();
        let mut result = Vec::new();
        visited[start] = true;
        queue.push_back(start);
        while let Some(index) = queue.pop_front() {
            result.push(self.nodes[index].value);
            for &neighbor in &self.nodes[index].edges {
                if !visited[neighbor] {
                    visited[neighbor] = true;
                    queue.push_back(neighbor);
                }
            }
        }
        result
    }
}

Marking nodes visited before enqueuing rather than after dequeuing prevents the same node from being enqueued multiple times in graphs where multiple edges lead to the same destination.

Depth-first search

DFS goes as deep as possible along each path before backtracking. The recursive version takes slices rather than Vec references, since the function only needs indexed mutation and does not require Vec-specific operations:

Vec {
let mut visited = vec![false; self.nodes.len()];
let mut result = Vec::new();
self.dfs_recursive(start, &mut visited, &mut result);
result
}

fn dfs_recursive(
&self,
index: usize,
visited: &mut [bool],
result: &mut Vec,
) {
if visited[index] {
return;
}
visited[index] = true;
result.push(self.nodes[index].value);
for &neighbor in &self.nodes[index].edges {
self.dfs_recursive(neighbor, visited, result);
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

impl Graph {
    fn dfs(&self, start: usize) -> Vec<i32> {
        let mut visited = vec![false; self.nodes.len()];
        let mut result = Vec::new();
        self.dfs_recursive(start, &mut visited, &mut result);
        result
    }

fn dfs_recursive(
        &self,
        index: usize,
        visited: &mut [bool],
        result: &mut Vec<i32>,
    ) {
        if visited[index] {
            return;
        }
        visited[index] = true;
        result.push(self.nodes[index].value);
        for &neighbor in &self.nodes[index].edges {
            self.dfs_recursive(neighbor, visited, result);
        }
    }
}
impl Graph {
    fn dfs(&self, start: usize) -> Vec<i32> {
        let mut visited = vec![false; self.nodes.len()];
        let mut result = Vec::new();
        self.dfs_recursive(start, &mut visited, &mut result);
        result
    }

fn dfs_recursive(
        &self,
        index: usize,
        visited: &mut [bool],
        result: &mut Vec<i32>,
    ) {
        if visited[index] {
            return;
        }
        visited[index] = true;
        result.push(self.nodes[index].value);
        for &neighbor in &self.nodes[index].edges {
            self.dfs_recursive(neighbor, visited, result);
        }
    }
}

The iterative version avoids stack overflow on very deep graphs:

Vec {
let mut visited = vec![false; self.nodes.len()];
let mut stack = Vec::new();
let mut result = Vec::new();

stack.push(start);
while let Some(index) = stack.pop() {
if visited[index] {
continue;
}
visited[index] = true;
result.push(self.nodes[index].value);
for &neighbor in self.nodes[index].edges.iter().rev() {
if !visited[neighbor] {
stack.push(neighbor);
}
}
}
result
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn dfs_iterative(&self, start: usize) -> Vec<i32> {
    let mut visited = vec![false; self.nodes.len()];
    let mut stack = Vec::new();
    let mut result = Vec::new();

    stack.push(start);
    while let Some(index) = stack.pop() {
        if visited[index] {
            continue;
        }
        visited[index] = true;
        result.push(self.nodes[index].value);
        for &neighbor in self.nodes[index].edges.iter().rev() {
            if !visited[neighbor] {
                stack.push(neighbor);
            }
        }
    }
    result
}
fn dfs_iterative(&self, start: usize) -> Vec<i32> {
    let mut visited = vec![false; self.nodes.len()];
    let mut stack = Vec::new();
    let mut result = Vec::new();

    stack.push(start);
    while let Some(index) = stack.pop() {
        if visited[index] {
            continue;
        }
        visited[index] = true;
        result.push(self.nodes[index].value);
        for &neighbor in self.nodes[index].edges.iter().rev() {
            if !visited[neighbor] {
                stack.push(neighbor);
            }
        }
    }
    result
}

Cycle detection

Detecting whether a directed graph contains a cycle uses DFS with three states per node: unvisited, currently being explored (in the active DFS path), and fully explored. Reaching a node marked InProgress means you have found a back edge, which means a cycle exists.

bool {
let mut state = vec![NodeState::Unvisited; self.nodes.len()];
for start in 0..self.nodes.len() {
if state[start] == NodeState::Unvisited {
if self.dfs_cycle_check(start, &mut state) {
return true;
}
}
}
false
}
fn dfs_cycle_check(&self, index: usize, state: &mut [NodeState]) -> bool {
state[index] = NodeState::InProgress;
for &neighbor in &self.nodes[index].edges {
match state[neighbor] {
NodeState::InProgress => return true,
NodeState::Unvisited => {
if self.dfs_cycle_check(neighbor, state) {
return true;
}
}
NodeState::Done => {}
}
}
state[index] = NodeState::Done;
false
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

#[derive(Clone, Copy, PartialEq)]
enum NodeState {
    Unvisited,
    InProgress,
    Done,
}

impl Graph {
    fn has_cycle(&self) -> bool {
        let mut state = vec![NodeState::Unvisited; self.nodes.len()];
        for start in 0..self.nodes.len() {
            if state[start] == NodeState::Unvisited {
                if self.dfs_cycle_check(start, &mut state) {
                    return true;
                }
            }
        }
        false
    }
    fn dfs_cycle_check(&self, index: usize, state: &mut [NodeState]) -> bool {
        state[index] = NodeState::InProgress;
        for &neighbor in &self.nodes[index].edges {
            match state[neighbor] {
                NodeState::InProgress => return true,
                NodeState::Unvisited => {
                    if self.dfs_cycle_check(neighbor, state) {
                        return true;
                    }
                }
                NodeState::Done => {}
            }
        }
        state[index] = NodeState::Done;
        false
    }
}
#[derive(Clone, Copy, PartialEq)]
enum NodeState {
    Unvisited,
    InProgress,
    Done,
}

impl Graph {
    fn has_cycle(&self) -> bool {
        let mut state = vec![NodeState::Unvisited; self.nodes.len()];
        for start in 0..self.nodes.len() {
            if state[start] == NodeState::Unvisited {
                if self.dfs_cycle_check(start, &mut state) {
                    return true;
                }
            }
        }
        false
    }
    fn dfs_cycle_check(&self, index: usize, state: &mut [NodeState]) -> bool {
        state[index] = NodeState::InProgress;
        for &neighbor in &self.nodes[index].edges {
            match state[neighbor] {
                NodeState::InProgress => return true,
                NodeState::Unvisited => {
                    if self.dfs_cycle_check(neighbor, state) {
                        return true;
                    }
                }
                NodeState::Done => {}
            }
        }
        state[index] = NodeState::Done;
        false
    }
}

#[derive(Clone, Copy, PartialEq)] is appropriate here because NodeState has no heap data, making it Copy rather than requiring clone allocations on state transitions.

Complexity

For a graph with V vertices and E edges:

Operation Complexity Add node O(1) amortised Add edge O(1) BFS O(V + E) DFS O(V + E) Cycle detection O(V + E) Space O(V + E)

The complete test suite

#[cfg(test)]
mod tests {
    use super::*;

#[test]
    fn bfs_visits_all_reachable_nodes() {
        let mut graph = Graph::new();
        let a = graph.add_node(1);
        let b = graph.add_node(2);
        let c = graph.add_node(3);
        let d = graph.add_node(4);
        graph.add_edge(a, b);
        graph.add_edge(a, c);
        graph.add_edge(b, d);
        let result = graph.bfs(a);
        assert_eq!(result, vec![1, 2, 3, 4]);
    }
    #[test]
    fn bfs_handles_cycles_without_infinite_loop() {
        let mut graph = Graph::new();
        let a = graph.add_node(1);
        let b = graph.add_node(2);
        graph.add_edge(a, b);
        graph.add_edge(b, a);
        let result = graph.bfs(a);
        assert_eq!(result.len(), 2);
    }
    #[test]
    fn cycle_detection_finds_cycle() {
        let mut graph = Graph::new();
        let a = graph.add_node(1);
        let b = graph.add_node(2);
        let c = graph.add_node(3);
        graph.add_edge(a, b);
        graph.add_edge(b, c);
        graph.add_edge(c, a);
        assert!(graph.has_cycle());
    }
    #[test]
    fn cycle_detection_no_false_positive() {
        let mut graph = Graph::new();
        let a = graph.add_node(1);
        let b = graph.add_node(2);
        let c = graph.add_node(3);
        graph.add_edge(a, b);
        graph.add_edge(a, c);
        assert!(!graph.has_cycle());
    }
    #[test]
    fn dfs_visits_nodes_in_depth_first_order() {
        let mut graph = Graph::new();
        let a = graph.add_node(1);
        let b = graph.add_node(2);
        let c = graph.add_node(3);
        let d = graph.add_node(4);
        graph.add_edge(a, b);
        graph.add_edge(b, d);
        graph.add_edge(a, c);
        let result = graph.dfs(a);
        assert_eq!(result, vec![1, 2, 4, 3]);
    }
}
#[cfg(test)]
mod tests {
    use super::*;

#[test]
    fn bfs_visits_all_reachable_nodes() {
        let mut graph = Graph::new();
        let a = graph.add_node(1);
        let b = graph.add_node(2);
        let c = graph.add_node(3);
        let d = graph.add_node(4);
        graph.add_edge(a, b);
        graph.add_edge(a, c);
        graph.add_edge(b, d);
        let result = graph.bfs(a);
        assert_eq!(result, vec![1, 2, 3, 4]);
    }
    #[test]
    fn bfs_handles_cycles_without_infinite_loop() {
        let mut graph = Graph::new();
        let a = graph.add_node(1);
        let b = graph.add_node(2);
        graph.add_edge(a, b);
        graph.add_edge(b, a);
        let result = graph.bfs(a);
        assert_eq!(result.len(), 2);
    }
    #[test]
    fn cycle_detection_finds_cycle() {
        let mut graph = Graph::new();
        let a = graph.add_node(1);
        let b = graph.add_node(2);
        let c = graph.add_node(3);
        graph.add_edge(a, b);
        graph.add_edge(b, c);
        graph.add_edge(c, a);
        assert!(graph.has_cycle());
    }
    #[test]
    fn cycle_detection_no_false_positive() {
        let mut graph = Graph::new();
        let a = graph.add_node(1);
        let b = graph.add_node(2);
        let c = graph.add_node(3);
        graph.add_edge(a, b);
        graph.add_edge(a, c);
        assert!(!graph.has_cycle());
    }
    #[test]
    fn dfs_visits_nodes_in_depth_first_order() {
        let mut graph = Graph::new();
        let a = graph.add_node(1);
        let b = graph.add_node(2);
        let c = graph.add_node(3);
        let d = graph.add_node(4);
        graph.add_edge(a, b);
        graph.add_edge(b, d);
        graph.add_edge(a, c);
        let result = graph.dfs(a);
        assert_eq!(result, vec![1, 2, 4, 3]);
    }
}

Production considerations

The index-based approach is not a workaround for Rust’s ownership system. Contiguous Vec<Node> storage gives cache-friendly memory layout, edge traversal accesses predictable memory locations, and adding nodes is O(1) amortised with no pointer update bookkeeping.

The tradeoff: indices become meaningless if you remove nodes. An index pointing to position 5 is stale if node 5 was removed. For use cases requiring frequent node removal, the tombstone pattern marks removed nodes as inactive rather than actually removing them. For more complex scenarios, arena allocators from crates like slotmap or generational-arena give stable handles with built-in generation counters, so stale references can be detected safely while keeping the ownership model of the index approach.

For dependency graphs, routing algorithms, state machines, and build systems, nodes are typically added but not removed, so the implementation above works as written.

The biggest lesson from implementing graphs in Rust is that ownership problems are often representation problems. When the data structure matches Rust’s ownership model, the compiler stops being an obstacle and becomes a design guide.

This is part of the Data Structures in Rust series. Previous articles cover linked lists, binary trees, hash maps, and stacks and queues.

LinkedList
Binary Tree
Hashmap
Stack and a Queue

Further reading and resources

f you want to go deeper on how Rust’s type system eliminates specific categories of these bugs at compile time, the field guide covers the ownership model, the borrow checker, and how they connect to the failures described here.

$7 — Zero to Rust: A Systems Programmer’s Field Guide
You can read the free sample here — Free 20-page sample