medium.com 5 min read Original Source

I Wanted a Parent Pointer in Rust. Here’s What the Borrow Checker Made Me Use.

I’d already built a tree with an index-based design, the workaround that keeps ownership simple by never letting a node hold a real reference to another node. Then I wanted something small and reasonable: let a child point back to its own parent. The compiler didn’t budge an inch. Two owners of the same node, at the same time, one of them wanting to mutate it, is precisely the shape of thing the borrow checker exists to refuse, and no amount of rearranging the code made it change its mind. The fix wasn’t a cleverer reference. It was giving up on plain references for this one specific job entirely.

Shared ownership needs a different kind of pointer altogether

A plain reference in Rust isn’t an owner at all. It borrows a value whose lifetime is controlled somewhere else, and the borrow checker’s whole job is proving, at compile time, that the borrow never outlives the value it’s pointing at. A parent-child structure where a child needs to reach its parent and the parent needs to reach its children is asking for something references were never built to provide: more than one legitimate owner of the same value, alive at the same time, with no single one of them clearly responsible for freeing it.

Rc<T>, reference counted, is Rust’s answer to that specific problem. Cloning an Rc doesn’t copy the data underneath it, it increments a counter and hands back another pointer to the exact same allocation. The value is only actually freed once every Rc pointing at it has been dropped and that counter reaches zero.

use std::rc::Rc;

let a = Rc::new(String::from("shared"));
let b = Rc::clone(&a); // same allocation, counter now at 2
use std::rc::Rc;

let a = Rc::new(String::from("shared"));
let b = Rc::clone(&a); // same allocation, counter now at 2

This solves shared ownership. It does not, on its own, solve mutation, and this is where I first assumed Rc was the whole answer and found out it wasn’t.

Why Rc alone won’t let you change anything

Rc<T> only ever hands out shared references to its contents, because the moment more than one owner exists, the compile-time guarantee that a mutable reference is always exclusive simply cannot be honored anymore. Two different owners cannot both safely believe they have the only path to mutate the same data, and the borrow checker has no way to arbitrate between them at compile time when both owners might be completely unaware of each other.

RefCell<T> is what makes mutation possible here, by moving the borrow check from compile time to runtime. Instead of the compiler proving there’s never more than one mutable borrow active, RefCell tracks that at runtime and panics the moment you actually violate it:

use std::cell::RefCell;

let cell = RefCell::new(5);
*cell.borrow_mut() += 1;      // fine, no other borrow is active
let _r1 = cell.borrow();
let _r2 = cell.borrow_mut(); // panics here, at runtime, not a compile error
use std::cell::RefCell;

let cell = RefCell::new(5);
*cell.borrow_mut() += 1;      // fine, no other borrow is active
let _r1 = cell.borrow();
let _r2 = cell.borrow_mut(); // panics here, at runtime, not a compile error

Combine the two and you get the pattern that actually solves the original problem: Rc<RefCell<T>>, shared ownership from the Rc, interior mutability from the RefCell. Multiple parts of a structure can each hold their own Rc pointing at the same node, and any of them can mutate it through the RefCell, with Rust checking the one rule that still has to hold, only one mutable borrow at a time, while the program is actually running instead of before it starts.

The cost nobody mentions until it bites you

The honest price of this pattern is worth stating plainly rather than glossing over, since it’s a real trade, not a free upgrade over plain references. A borrow violation that would have been a compile error with ordinary references is now a runtime panic with RefCell, discovered whenever that exact code path happens to run, not the moment you write it. Rc‘s reference counting isn’t free either, every clone and drop touches a counter, small, but not zero, and unlike an Arc, a plain Rc isn’t thread-safe at all, reaching for it across threads is a compile error waiting to redirect you toward Arc<Mutex<T>> instead.

The trap that actually matters: a cycle that leaks forever

Here’s the one genuinely dangerous part, and it’s the part most people building their first parent-child structure walk straight into. Give a parent an Rc pointing to its child, and give that child an Rc pointing straight back to its parent, and you’ve built a cycle. Each one is holding a reference count open on the other. Neither one’s count can ever reach zero, because each is kept alive by the other’s pointer to it, and Rust’s ownership model, for all its guarantees, does not include cycle detection for Rc. The memory leaks, silently, in a language famous for making you think you don’t have to worry about memory. Rust never actually promised leaks were impossible, only that certain classes of memory bugs, use-after-free, data races, are ruled out at compile time. A leaked Rc cycle is neither of those. It’s just memory nobody’s going to reclaim, sitting there for the life of the program, entirely within the rules.

<button data-code="use std::rc::{Rc, Weak};
use std::cell::RefCell;

struct Node {
value: i32,
parent: RefCell<Weak>, // does not keep the parent alive
children: RefCell<Vec<Rc>>, // does keep children alive
}” 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, Weak};
use std::cell::RefCell;

struct Node {
    value: i32,
    parent: RefCell<Weak<Node>>,       // does not keep the parent alive
    children: RefCell<Vec<Rc<Node>>>,  // does keep children alive
}
use std::rc::{Rc, Weak};
use std::cell::RefCell;

struct Node {
    value: i32,
    parent: RefCell<Weak<Node>>,       // does not keep the parent alive
    children: RefCell<Vec<Rc<Node>>>,  // does keep children alive
}

The fix is Weak<T>, a non-owning reference alongside Rc. A Weak pointer can observe whether the value it points to still exists, through .upgrade(), which hands back Some(Rc<T>) if the value is still alive or None if it’s already been dropped, but holding a Weak contributes nothing to the strong reference count, so it can never be the thing keeping a cycle alive.

if let Some(parent) = child.parent.borrow().upgrade() {
    // the parent is still alive; this is a real, temporary Rc to it
    println!("parent value: {}", parent.value);
} else {
    // the parent has already been dropped
}
if let Some(parent) = child.parent.borrow().upgrade() {
    // the parent is still alive; this is a real, temporary Rc to it
    println!("parent value: {}", parent.value);
} else {
    // the parent has already been dropped
}

Rc<Node> owns. Weak<Node> only ever gets to ask, right now, in this moment, does the thing I’m pointing at still exist, and it has to accept None as a real possible answer every time it asks. That single distinction, own versus merely observe, is the entire mechanism that breaks the cycle. The convention here is that parents hold Rc pointers to their children, and children hold Weak pointers back to their parents. Ownership flows one direction, down the tree, exactly the way it would in a tree built with any other technique, and the parent pointer riding along on top of it is observational, not an ownership claim.

What this actually teaches, once the specific pattern fades

Rc<RefCell<T>> isn’t a workaround to memorize and forget. It’s the moment ownership in Rust stops being one rule and becomes a design decision with real alternatives, each with its own honest cost: a plain reference when one owner is enough, an index into a flat structure when you want to sidestep ownership questions entirely, Rc<RefCell<T>> when you genuinely need more than one owner and are willing to pay for runtime checks and careful cycle-avoidance to get it. The parent pointer that started this was never really the point. The real lesson was learning to ask, for every pointer in a data structure: does this relationship own the thing, borrow it, or merely observe it?

Correction: An earlier version reversed the parent and child roles in one sentence. The code was correct. Thanks to David Harkness for catching it.

If you’re prepping for interviews or just want the fast reference: Rust vs. Java — The Data Structures Cheat Sheet is free — Big-O for every structure, the full 55-problem interview index by chapter, and the three rules that separate a senior answer from a junior one.

If you’re curious how these same ownership and collection questions play out on the Java side, that’s the whole premise of the book I’ve been writing: every classic data structure built once in Rust and once in Java, side by side, so you can see exactly where each language’s rules force a different decision. Ownership vs. Reference: Data Structures and Algorithms in Rust and Java — $9 · Free preview

For the Rust foundations that series builds on: Zero to Rust: A Systems Programmer’s Field Guide — $7 · Free 20-page sample