Command 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
- ✓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 Pattern in Rust: what you actually reach for
Rust implementation
// 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 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 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).
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 trialStudying for this? Devin free tiers and academic plans are laid out 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.