rust
39 lines · 8 steps
A RAII rollback guard in Rust
A ScopeGuard runs a compensating action on drop unless you commit, giving you automatic rollback on early return.
Explained by
highlit
1pub struct ScopeGuard<F: FnMut()> {
2 rollback: F,
3 active: bool,
4}
5
6impl<F: FnMut()> ScopeGuard<F> {
7 pub fn new(rollback: F) -> Self {
8 Self { rollback, active: true }
9 }
10
11 pub fn commit(mut self) {
12 self.active = false;
13 }
14}
15
16impl<F: FnMut()> Drop for ScopeGuard<F> {
17 fn drop(&mut self) {
18 if self.active {
19 (self.rollback)();
20 }
21 }
22}
23
24pub fn apply_credit(account: &Rc<RefCell<Account>>, amount: u64) -> Result<(), TransferError> {
25 account.borrow_mut().balance += amount;
26
27 let guard = {
28 let account = Rc::clone(account);
29 ScopeGuard::new(move || {
30 account.borrow_mut().balance -= amount;
31 })
32 };
33
34 ledger::record(account.borrow().id, amount)?;
35 notify::credit_applied(account.borrow().id, amount)?;
36
37 guard.commit();
38 Ok(())
39}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1RAII lets you tie cleanup to scope exit so every early return runs it automatically.
- 2Consuming self in a method disarms a guard by moving it out of drop's reach at commit time.
- 3Capturing a cloned Rc by move lets the rollback closure outlive the surrounding block.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
rust
use std::cmp::Ordering; pub struct PrefixIndex { entries: Vec<String>,
Prefix search with binary partitioning in Rust
binary-search
sorting
case-insensitive
Intermediate
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-raii-rollback-guard-in-rust-explained-rust-6013/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.