Smart Pointers · 18 min · free lesson

Reference Cycles

Rust prevents data races, not leaks — a cycle can still strand memory.

Core idea

Weak does not keep a value alive, so upgrade() may return None.

Two strong Rc links form a cycle; replacing the back link with Weak breaks the strong cycle.
A weak back link permits cleanup after external owners go away.

Understand it

Two Rc handles pointing at each other never reach a count of zero, so neither is freed. Weak<T> is the answer: it does not count towards ownership and must be upgraded before use, which turns a parent pointer into something that can legitimately be gone.

Reference counting releases an allocation only when its strong count reaches zero. If node A owns an Rc to B and B owns an Rc back to A, each keeps the other alive after all outside handles are dropped. Rust prevents memory unsafety here, but the allocations leak. A graph needs a deliberate ownership direction, not strong links in every direction.

A common tree design lets a parent own children through strong Rc handles while each child keeps a Weak reference back to its parent. A weak reference does not keep the parent alive. upgrade() returns an Option<Rc<T>>, because the parent may have been dropped. That absence is a normal state to handle, not an exceptional failure. In the sample, Rc::downgrade stores the parent link, and the Option from upgrade() is checked before reading through it.

Draw two nodes and label the strong links before writing code. Remove all external owners on paper: if every node still has an incoming strong link from within the cycle, cleanup cannot begin. Replace one direction with weak links and repeat the count. For practice, create a parent and child, then drop the parent and verify that upgrading the child's weak parent link returns None if the child is still held externally. The lesson is not to avoid shared ownership entirely, but to make the owning direction explicit.

Weak references can also be used for caches that should not keep objects alive. The caller must accept that upgrade() may return None; a weak link is a question about whether the target still exists, not an ownership guarantee. Draw strong and weak edges with different arrows during review.

Read the code

use std::cell::RefCell;
use std::rc::{Rc, Weak};

struct Node {
    value: i32,
    parent: RefCell<Weak<Node>>,
    children: RefCell<Vec<Rc<Node>>>,
}

let leaf = Rc::new(Node {
    value: 3,
    parent: RefCell::new(Weak::new()),
    children: RefCell::new(vec![]),
});
let branch = Rc::new(Node {
    value: 5,
    parent: RefCell::new(Weak::new()),
    children: RefCell::new(vec![Rc::clone(&leaf)]),
});
*leaf.parent.borrow_mut() = Rc::downgrade(&branch);

let parent = leaf.parent.borrow().upgrade();
println!("parent {:?}", parent.map(|node| node.value));

The child points back with Weak, so the cycle never forms.

Practice starter

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

#[derive(Default)]
struct Node {
    parent: RefCell<Option<Rc<Node>>>,
    children: RefCell<Vec<Rc<Node>>>,
}

let parent = Rc::new(Node::default());
let child = Rc::new(Node::default());
parent.children.borrow_mut().push(Rc::clone(&child));
*child.parent.borrow_mut() = Some(Rc::clone(&parent));
println!("{}", Rc::strong_count(&parent));

Practise this code in Playground ↗

Try it

Explain where a parent pointer should be Weak rather than Rc.

What success looks like: You can name which direction owns and which merely observes.

Check your understanding

Why should that parent link be Weak?

Reveal the answer
  1. A Weak link is cheaper to clone than an Rc
  2. Two Rc links in a cycle never reach zero, so nothing is freed
  3. The compiler refuses to build a cyclic Rc graph

Ownership should flow one way; the back-reference observes without owning.

Go deeper

Common misconception: “Rust's ownership rules stop reference cycles from leaking.”

The compiler accepts a strong cycle, and its counts never reach zero. Weak does not keep a value alive, so a weak back link breaks the cycle and upgrade() may return None.

  1. Build the leaf: leaf starts with an empty Weak::new() parent, so upgrading at that point would return None.
  2. Link both ways: branch owns leaf through a strong Rc in children, while Rc::downgrade(&branch) stores only a weak link in leaf.parent.
  3. Upgrade the link: upgrade() returns Some while branch is alive, so this prints parent Some(5). After branch is dropped it would return None.

Transfer challenge: Change the practice's parent field to RefCell<Weak<Node>> and store Rc::downgrade(&parent). Predict Rc::strong_count(&parent) and Rc::weak_count(&parent), then print both.

Connections

  • Deref & Drop: Making a type behave like a reference
  • Package Layout: Map Cargo targets to predictable source paths
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Reference Cycles (courseId "projects", lessonId "cycles")
Link: https://crabrix.com/learn/projects/cycles/
Goal: Weak does not keep a value alive, so upgrade() may return None.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=projects/cycles) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.