Composite Pattern Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Composite Pattern runs in O(n) time and O(n) space, in Rust as in every other language.
- ✓A recursive type must have a known size, so the child must sit behind an indirection: Box<Node> for sole ownership, Rc<Node> for shared, or simply Vec<Node>, which already holds its elements on the heap and is the usual answer for a composite.
- ✓Use Vec<Node> for children and reach for Rc only when nodes are genuinely shared between trees; a Rust reviewer will ask why Rc<RefCell<>> appeared before asking whether it is correct, because it moves the borrow check to run time.
- ✓The Rust trap: Two failures, and the second one surprises even experienced users. First, a parent pointer stored as Rc creates a cycle that std::rc will never collect, so the entire tree leaks with no error and no panic; Weak is the only fix.
- ✓Vec<Node> stores nodes contiguously, so a breadth-first walk over one level is cache friendly in a way that a Box-per-node tree never is; Box<Node> per child costs one allocation and one pointer chase per node.
What Composite Pattern actually is
Composite Pattern in Rust: what you actually reach for
Rust implementation
use std::rc::{Rc, Weak};
use std::cell::RefCell;
pub enum Node {
Leaf(u64),
Branch(Vec<Node>), // Vec already heaps its elements: no Box needed
}
impl Node {
pub fn total(&self) -> u64 {
match self {
Node::Leaf(n) => *n,
Node::Branch(kids) => kids.iter().map(Node::total).sum(),
}
}
// Iterative: recursion would risk a stack overflow on a deep tree.
pub fn total_iter(&self) -> u64 {
let (mut stack, mut acc) = (vec![self], 0);
while let Some(n) = stack.pop() {
match n {
Node::Leaf(v) => acc += v,
Node::Branch(kids) => stack.extend(kids.iter()),
}
}
acc
}
}
// Parent pointers: the child link is Rc, the BACK link must be Weak
// or the whole tree leaks, std::rc has no cycle collector.
pub struct Tree {
parent: RefCell<Weak<Tree>>,
children: RefCell<Vec<Rc<Tree>>>,
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Composite Pattern?
A recursive type must have a known size, so the child must sit behind an indirection: Box<Node> for sole ownership, Rc<Node> for shared, or simply Vec<Node>, which already holds its elements on the heap and is the usual answer for a composite. Adding a parent pointer requires Rc<RefCell<Node>> for the child links and Weak<RefCell<Node>> for the back link, because std::rc is reference counting with no cycle collector. The enum-with-Box form is how the standard library models recursive structures such as syntax trees.
What is the most common Rust mistake when implementing Composite Pattern?
Two failures, and the second one surprises even experienced users. First, a parent pointer stored as Rc creates a cycle that std::rc will never collect, so the entire tree leaks with no error and no panic; Weak is the only fix. Second, the DERIVED Drop is recursive: dropping the root drops its children, which drop theirs, so a very deep tree, and especially a degenerate list-shaped one, overflows the stack inside the destructor, where you cannot catch it. Long linked structures therefore need a manual iterative Drop implementation, which is a documented hazard for Box-based lists.
How does Composite Pattern actually perform in Rust?
Vec<Node> stores nodes contiguously, so a breadth-first walk over one level is cache friendly in a way that a Box-per-node tree never is; Box<Node> per child costs one allocation and one pointer chase per node. Rc adds a non-atomic refcount increment per clone and RefCell adds a runtime borrow flag check per access, which also prevents the optimiser from proving that two references do not alias. An arena, where nodes live in one Vec and children are stored as indices, removes all of that and is the standard high-performance layout for trees in Rust. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.