Course contentsShow
← Rust
Lesson 998 of 1,9109. Smart Pointers and Interior MutabilityFree lesson

The Limitations of Single Ownership

Identify scenarios where unique ownership prevents valid graph data structures.

In this lesson, you will learn why Rust’s strict single-ownership model creates a fundamental conflict when building complex, interconnected data structures like graphs.

The Ownership Bottleneck

Up until now, we have used Box<T> to manage memory on the heap. While Box is excellent for tree-like structures where a parent node "owns" its children, it enforces a strict hierarchy: every piece of data must have one, and only one, owner.

In a graph, this ownership model collapses. Consider a simple directed graph where nodes point to each other. If Node A points to Node B, Node A must own Node B to ensure it stays in memory. But what happens if Node C also needs to point to Node B?

If Node A owns Node B, Node C cannot also "own" it in the way the compiler expects. If we try to share Node B between two owners, we violate the single-ownership rule. Rust’s borrow checker would prevent this because if Node A were to drop, Node B would be deallocated, leaving Node C with a dangling pointer.

The Graph Dilemma

struct Node {
    value: i32,
    neighbors: Vec<Box<Node>>, // Only works for trees/DAGs
}

In this implementation, the Vec owns its children. If you try to represent a cycle (e.g., Node A points to Node B, and Node B points back to Node A), you hit a logical wall. You cannot have two Box<Node> instances owning each other, as that would result in an infinite size requirement at compile time and a memory leak at runtime.

Even without cycles, any structure where multiple nodes need to reference a single shared resource creates a "multiple-owner" problem. In languages with garbage collection, this is handled by tracking references. In Rust, however, the compiler’s mandate that memory must have a deterministic owner at any given time means that simple heap pointers (Box) are insufficient for complex, non-hierarchical data structures. To represent these graphs safely, we must move beyond the rigid constraints of single ownership.

Key Takeaway: Single ownership via Box creates rigid hierarchies; graphs require multiple references to the same memory, which fundamentally conflicts with the "one owner" rule of heap-allocated Box pointers.