Memento 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
- ✓Memento Pattern runs in O(1) time and O(n) space, in Rust as in every other language.
- ✓Clone is the snapshot and the type system does the rest. serde with a derive gives serialisation to JSON, MessagePack or anything else for a persisted checkpoint.
- ✓Make the memento a distinct struct with private fields in its own module, so the caretaker holds it and cannot inspect it; Rust module privacy gives the encapsulation directly.
- ✓The Rust trap: The mistake other languages make silently is a compile error here: you cannot hold a snapshot that aliases the live object, because either the memento owns its data or it borrows it, and if it borrows, the borrow checker forbids mutating the originator while the snapshot is alive.
- ✓Cloning a state struct allocates once per owned field, so a state of five Strings and a Vec is seven allocations per snapshot; flattening state into a single buffer or interning strings cuts that sharply.
What Memento Pattern actually is
Memento Pattern in Rust: what you actually reach for
Rust implementation
mod editor {
#[derive(Clone, Default, Debug)]
struct State { text: String, cursor: usize }
// Private field: the caretaker can hold a Memento and cannot look inside.
pub struct Memento(State);
#[derive(Default)]
pub struct Editor { state: State }
impl Editor {
pub fn save(&self) -> Memento { Memento(self.state.clone()) }
pub fn restore(&mut self, m: Memento) {
self.state = m.0; // MOVES in: no second clone
}
pub fn take_state(&mut self) -> Memento {
// mem::take moves the state out and leaves Default behind. Free.
Memento(std::mem::take(&mut self.state))
}
pub fn type_text(&mut self, s: &str) {
self.state.text.push_str(s);
self.state.cursor += s.len();
}
}
}
// The classic aliasing bug is UNWRITEABLE: a borrowing memento would forbid
// mutating the editor while it is alive, so the compiler rejects it outright.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 Memento Pattern?
Clone is the snapshot and the type system does the rest. serde with a derive gives serialisation to JSON, MessagePack or anything else for a persisted checkpoint. Cow defers the copy until a mutation, and for an undo history the usual choice is either a Vec of cloned states or a Vec of inverse operations, exactly as elsewhere. std::mem::replace and std::mem::take swap a value out and leave a default behind, which is the idiomatic way to move state into a memento without a clone at all.
What is the most common Rust mistake when implementing Memento Pattern?
The mistake other languages make silently is a compile error here: you cannot hold a snapshot that aliases the live object, because either the memento owns its data or it borrows it, and if it borrows, the borrow checker forbids mutating the originator while the snapshot is alive. So the classic bug of restoring from a memento that has been mutating along with the object cannot be written. What does bite is the opposite: an attempt to store a borrowed memento forces a lifetime parameter onto the struct, which then propagates through every type that holds it, and the practical answer is almost always to own the data.
How does Memento Pattern actually perform in Rust?
Cloning a state struct allocates once per owned field, so a state of five Strings and a Vec is seven allocations per snapshot; flattening state into a single buffer or interning strings cuts that sharply. mem::take moves rather than copies and is free. For long histories the memory story is the same as everywhere, but Rust makes the delta approach pleasant because an enum of inverse operations is cheap, exhaustively matched and serialisable. 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 for Devin, check its student and free-tier options 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.