E0072
Rust Compiler Error
Severity: ModerateWhat Does This Error Mean?
Rust E0072 means you defined a struct or enum that contains itself directly, which would require infinite memory. The fix is to wrap the recursive field in Box<T>, which stores it on the heap with a fixed pointer size.
Affected Models
- Rust (all stable versions)
Common Causes
- Struct defined with a field of its own type (e.g. struct Node { next: Node })
- Enum variant containing the enum itself — common in linked lists and tree nodes
- Mutually recursive types without indirection (A contains B, B contains A)
- Forgetting that Rust must know the exact size of all types at compile time
How to Fix It
-
Wrap the recursive field in Box<T>.
Change: next: Node to: next: Box<Node> Box stores the value on the heap — a Box pointer is always a fixed size (8 bytes on 64-bit), breaking the infinite size loop.
-
For optional recursive fields, use Option<Box<T>>.
For linked lists and trees where the next node may not exist: next: Option<Box<Node>> None represents the end of the chain, Some(Box::new(node)) adds the next element.
-
For shared or cyclic references, consider Rc<T> or Arc<T> instead of Box<T>.
Box<T> gives unique ownership. Rc<T> allows shared ownership (single-threaded). Arc<T> allows shared ownership across threads. For tree nodes with parent pointers, Rc<RefCell<T>> is the common pattern.
Frequently Asked Questions
Why does Rust need to know the size of all types at compile time?
Rust allocates local variables on the stack, which requires knowing their exact size before running. An infinite recursive type has no finite size, so it cannot be placed on the stack. Box moves the value to the heap, where size is determined at runtime.
Is Box<T> expensive to use?
Box requires a single heap allocation per value, which is slightly slower than stack allocation. For recursive types like linked lists and trees, this cost is unavoidable and completely normal. For non-recursive types, prefer stack allocation where possible.