Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Decorator Pattern Implementation in Rust

14 min readintermediate
Website QA and SEO audits

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

The Decorator pattern adds behaviour to an individual object by wrapping it in another object that implements the same interface and forwards to it, so you can stack capabilities (buffering, then compression, then encryption) without a combinatorial explosion of subclasses. Its defining property is that the decorator is INDISTINGUISHABLE from the thing it decorates at the type level, which is what makes stacking work. Reading about it across these eight languages is unusually confusing for one reason: Python, TypeScript and Swift all have a LANGUAGE feature called a decorator or a wrapper that is related but not the same thing, Python decorators transform functions and classes at definition time, TypeScript has two mutually incompatible decorator systems, and Swift property wrappers decorate storage. Meanwhile Go gets the pattern almost for free through embedding, and Rust has no inheritance to avoid in the first place.

Decorator Pattern in Rust: what you actually reach for

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.

Rust implementation

Prefer the generic wrapper and let the compiler specialise it; reach for Box<dyn Trait> only when the composition is decided at runtime. Keep the trait small so forwarding is short, and use a delegation macro or the ambassador crate when a trait has many methods. Expose into_inner() so callers can unwrap the decoration, matching the convention BufWriter and friends follow.
rust
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 Free

The Rust-specific 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. 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.

Performance in Rust, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Decorator Pattern between languages.

Real-World Applications

Decorator Pattern is used extensively in production software: framework internals, plugin architectures, state management libraries, and large-scale application architectures all rely on this pattern. In Rust, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Decorator Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Decorator Pattern appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Decorator Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Decorator Pattern to build pattern recognition. In Rust, demonstrate proficiency with ownership system and pattern matching to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Rust code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.