Auto-Rollback Uncommitted State With Drop
Build a RAII scope guard implementing Drop so uncommitted mutations roll back to a checkpoint on early return unless commit is called.
Code
struct StagingGuard<'a> {
log: &'a mut Vec<&'static str>,
checkpoint: usize,
committed: bool,
}
impl<'a> StagingGuard<'a> {
fn begin(log: &'a mut Vec<&'static str>) -> Self {
let checkpoint = log.len();
Self { log, checkpoint, committed: false }
}
fn push(&mut self, entry: &'static str) {
self.log.push(entry);
}
fn commit(mut self) {
self.committed = true;
}
}
impl Drop for StagingGuard<'_> {
fn drop(&mut self) {
if !self.committed {
self.log.truncate(self.checkpoint);
}
}
}
fn apply_batch(log: &mut Vec<&'static str>, should_fail: bool) -> Result<(), &'static str> {
let mut guard = StagingGuard::begin(log);
guard.push("step-1");
guard.push("step-2");
if should_fail {
return Err("validation aborted"); // guard drops uncommitted -> rolls back
}
guard.commit();
Ok(())
}
fn main() {
let mut history = vec!["init"];
println!("aborted: {:?}", apply_batch(&mut history, true));
println!("after rollback: {history:?}");
println!("succeeded: {:?}", apply_batch(&mut history, false));
println!("after commit: {history:?}");
}Implementation flow — Auto-Rollback Uncommitted State With Drop
Auto-Rollback Uncommitted State With Drop reduces to the functions begin, push, commit and drop.
Fallible operations return Result, forcing the caller to handle both arms explicitly.
Watch out for
- Zero setup commands needed because every used API ships natively with the runtime.
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Putting it to use
The entry-point signature is fn begin(log: &'a mut Vec<&'static str>) -> Self
The run emits 4 labeled sections — aborted:, after rollback:, succeeded:, after commit: — one per step.
main sequences apply_batch; executing the file runs that flow once.
Core lines
return Err("validation aborted"); // guard drops uncommitted -> rolls back
}
fn begin(log: &'a mut Vec<&'static str>) -> Self {
let checkpoint = log.len();
Self { log, checkpoint, committed: false }
}
fn push(&mut self, entry: &'static str) {
self.log.push(entry);
}
Interactive Tools for This Topic
FAQ
- How should callers handle failures?
- Through `Result` values. Nothing panics inside the snippet; the caller decides how to handle each failure.
- What does Auto-Rollback Uncommitted State With Drop print when run?
- The script runs standalone; its 4 labeled outputs include `aborted:`, `after rollback:`, `succeeded:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.