Smart Pointers · 18 min · free with an account

Reference Cycles

Lesson preview · about 30%

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.

Start with the idea

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.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Cargo & Real Projects