Decorator 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
- ✓Decorator Pattern runs in O(1) time and O(n) space, in Rust as in every other language.
- ✓Rust has no inheritance, so there is no subclass explosion to avoid and the pattern reduces to its essence: a struct that holds an inner value and implements the same trait.
- ✓Prefer the generic wrapper and let the compiler specialise it; reach for Box<dyn Trait> only when the composition is decided at runtime.
- ✓The Rust trap: There is no automatic method forwarding, so every trait method must be written out by hand, and the tempting shortcut, implementing Deref to the inner type, does NOT make the wrapper satisfy the inner type trait bounds.
- ✓The generic wrapper is a genuine zero-cost abstraction: after monomorphisation and inlining, a three-layer stack of generic decorators compiles to the same instructions as the undecorated call, and the wrapper struct itself usually occupies no extra space beyond the inner value.
What Decorator Pattern actually is
Decorator Pattern in Rust: what you actually reach for
Rust implementation
use std::time::Instant;
pub trait Store {
fn get(&self, key: &str) -> Option<String>;
}
pub struct Memory(std::collections::HashMap<String, String>);
impl Store for Memory {
fn get(&self, key: &str) -> Option<String> { self.0.get(key).cloned() }
}
/// Generic decorator: monomorphised, inlined, ZERO cost.
pub struct Timed<S: Store> {
inner: S,
}
impl<S: Store> Timed<S> {
pub fn new(inner: S) -> Self { Self { inner } }
pub fn into_inner(self) -> S { self.inner } // convention: allow unwrapping
}
impl<S: Store> Store for Timed<S> {
fn get(&self, key: &str) -> Option<String> {
let t0 = Instant::now();
let out = self.inner.get(key); // forward by hand
eprintln!("get {} took {:?}", key, t0.elapsed());
out
}
}
// Deref does NOT satisfy trait bounds. A Deref-based "decorator" gets you
// method-call sugar and then fails the moment someone writes
// fn use_store<S: Store>(s: S)
// The Rust API guidelines advise against Deref for anything but smart pointers.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(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Decorator Pattern?
Rust has no inheritance, so there is no subclass explosion to avoid and the pattern reduces to its essence: a struct that holds an inner value and implements the same trait. Two forms exist. The generic form, struct Timed<S: Store>(S), monomorphises and costs nothing. The dynamic form, struct Timed(Box<dyn Store>), allows a stack assembled at runtime at the price of a vtable call. std::io is built exactly this way, BufReader<R: Read> wraps any reader.
What is the most common Rust mistake when implementing Decorator Pattern?
There is no automatic method forwarding, so every trait method must be written out by hand, and the tempting shortcut, implementing Deref to the inner type, does NOT make the wrapper satisfy the inner type trait bounds. Deref gives you method-call sugar, not trait implementation, so a Deref-based decorator compiles until someone passes it to a function generic over the trait and then fails with a confusing bound error. The Rust API guidelines explicitly warn against Deref for anything other than smart pointers.
How does Decorator Pattern actually perform in Rust?
The generic wrapper is a genuine zero-cost abstraction: after monomorphisation and inlining, a three-layer stack of generic decorators compiles to the same instructions as the undecorated call, and the wrapper struct itself usually occupies no extra space beyond the inner value. Box<dyn Trait> costs one heap allocation per layer plus an indirect call per method, which blocks inlining across the boundary, the difference is measurable in tight loops and irrelevant for I/O. Time complexity is O(1) 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 trialBefore paying full price for a tool, check the student deals on AI and developer tools listed 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.