实现说明
利用 Drop 实现未提交状态的自动回滚守卫以函数 begin、push、commit、drop为骨架。
可能失败的操作返回 Result,调用方必须显式处理两个分支。
使用要点
- 纯标准库——复制进去就能跑。
- 错误走
Result通道;改编时若去掉?,每个调用点都要自己match。 - 每一步打印都带着自己的标签:
aborted:、after rollback:、succeeded:。 main按顺序串起apply_batch;运行文件就会把这个流程跑一遍。
常见问题
调用方该如何处理失败?
通过 Result 值。示例内部没有 panic,如何处理每次失败由调用方决定。
运行「利用 Drop 实现未提交状态的自动回滚守卫」会打印什么?
文件本身就是完整程序,直接运行——输出行带有 aborted:、after rollback:、succeeded: 这类标签。
签名一览:fn begin(log: &'a mut Vec<&'static str>) -> Self
核心语句
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);
}
代码示例
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:?}");
}