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

Command 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

  • ✓Command Pattern runs in O(1) time and O(n) space, in Rust as in every other language.
  • ✓The closure form is Box<dyn FnOnce()> for a command that runs once and consumes what it captured, or Box<dyn Fn()> for one that can run repeatedly.
  • ✓Model commands as an enum and derive Serialize and Deserialize; a Rust reviewer will prefer that to trait objects because it gives exhaustive matching and lets the compiler find every site that must handle a new command.
  • ✓The Rust trap: Ownership makes the one-shot nature of a command explicit and beginners fight it: a closure that captures a String by move can only be called once, so storing it as Box<dyn Fn()> fails to compile with a message about moving out of a captured variable, and the fix is Box<dyn FnOnce()>, which then cannot be stored in a Vec you iterate by reference because calling it consumes it.
  • ✓The enum form needs no allocation and matches on a discriminant the optimiser can turn into a jump table, so a command queue of enums is a contiguous Vec with excellent locality.

What Command Pattern actually is

Command turns an action into an object, so it can be stored, queued, logged, retried, sent across a process boundary, and undone. The moment you want undo or persistence, one property decides the whole design: is the command DATA or is it CODE? A closure that captures its arguments is code, and it is the most convenient thing to write in every language here, but it cannot be serialised, inspected, replayed after a restart or sent to another machine. A record describing the action is data, and it can do all of those but has to be interpreted. Beyond that split, the eight languages diverge on who owns a captured value, whether a command may be invoked only once, and whether the platform already ships an undo stack you should be using instead of writing your own.

Command Pattern in Rust: what you actually reach for

The closure form is Box<dyn FnOnce()> for a command that runs once and consumes what it captured, or Box<dyn Fn()> for one that can run repeatedly. Calling a boxed FnOnce has been possible since Rust 1.35, which removed the old FnBox workaround that older articles still describe. The data form is an enum with one variant per command plus a match, and it is what most Rust codebases actually use because it is serialisable with serde, exhaustively matched, and needs no allocation. std::sync::mpsc gives a command queue between threads.

Rust implementation

Model commands as an enum and derive Serialize and Deserialize; a Rust reviewer will prefer that to trait objects because it gives exhaustive matching and lets the compiler find every site that must handle a new command. When you do need the trait-object form, name the method execute and take self by value if it runs once, which encodes the one-shot nature in the type rather than in a comment. Return Result from execute rather than panicking.
rust
// DATA form: no allocation, exhaustive, serialisable.
#[derive(Debug, Clone)]
pub enum Command {
    Set { key: String, value: i64, prev: Option<i64> },
    Delete { key: String, prev: Option<i64> },
}

use std::collections::HashMap;

impl Command {
    pub fn apply(&self, store: &mut HashMap<String, i64>) {
        match self {
            Command::Set { key, value, .. } => { store.insert(key.clone(), *value); }
            Command::Delete { key, .. } => { store.remove(key); }
        }
    }
    pub fn revert(&self, store: &mut HashMap<String, i64>) {
        let (key, prev) = match self {
            Command::Set { key, prev, .. } | Command::Delete { key, prev } => (key, prev),
        };
        match prev {
            Some(v) => { store.insert(key.clone(), *v); }
            None => { store.remove(key); }
        }
    }
}

// CODE form: FnOnce encodes "runs exactly once" in the TYPE.
pub struct Queue { jobs: Vec<Box<dyn FnOnce() + Send>> }

impl Queue {
    pub fn run(self) {                // takes self: the queue is consumed
        for job in self.jobs {        // into_iter, not iter: calling MOVES the box
            job();
        }
    }
}

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

Ownership makes the one-shot nature of a command explicit and beginners fight it: a closure that captures a String by move can only be called once, so storing it as Box<dyn Fn()> fails to compile with a message about moving out of a captured variable, and the fix is Box<dyn FnOnce()>, which then cannot be stored in a Vec you iterate by reference because calling it consumes it. Draining the vector with into_iter, rather than iterating it, is the answer. The other trap is that Box<dyn FnOnce()> is not Send by default, so a command queue crossing threads needs the explicit Send bound.

Performance in Rust, beyond the O(1)

The enum form needs no allocation and matches on a discriminant the optimiser can turn into a jump table, so a command queue of enums is a contiguous Vec with excellent locality. Each Box<dyn FnOnce> is a separate allocation plus a fat pointer and an indirect call, so a queue of a million boxed closures is a million allocations. Undo histories are therefore substantially cheaper as enums, and the serde derive comes free with that choice. 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 Command Pattern between languages.

Real-World Applications

Command 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 Command Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Command 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 Command 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 Command 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 Command Pattern?

The closure form is Box<dyn FnOnce()> for a command that runs once and consumes what it captured, or Box<dyn Fn()> for one that can run repeatedly. Calling a boxed FnOnce has been possible since Rust 1.35, which removed the old FnBox workaround that older articles still describe. The data form is an enum with one variant per command plus a match, and it is what most Rust codebases actually use because it is serialisable with serde, exhaustively matched, and needs no allocation. std::sync::mpsc gives a command queue between threads.

What is the most common Rust mistake when implementing Command Pattern?

Ownership makes the one-shot nature of a command explicit and beginners fight it: a closure that captures a String by move can only be called once, so storing it as Box<dyn Fn()> fails to compile with a message about moving out of a captured variable, and the fix is Box<dyn FnOnce()>, which then cannot be stored in a Vec you iterate by reference because calling it consumes it. Draining the vector with into_iter, rather than iterating it, is the answer. The other trap is that Box<dyn FnOnce()> is not Send by default, so a command queue crossing threads needs the explicit Send bound.

How does Command Pattern actually perform in Rust?

The enum form needs no allocation and matches on a discriminant the optimiser can turn into a jump table, so a command queue of enums is a contiguous Vec with excellent locality. Each Box<dyn FnOnce> is a separate allocation plus a fat pointer and an indirect call, so a queue of a million boxed closures is a million allocations. Undo histories are therefore substantially cheaper as enums, and the serde derive comes free with that choice. 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

Studying for this? Devin free tiers and academic plans are laid out 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.