From 42a423764e7dd3aa7eb42c54a218d4acbd20f6ee Mon Sep 17 00:00:00 2001 From: Glen De Cauwsemaecker Date: Sat, 2 Aug 2025 10:59:24 +0200 Subject: [PATCH] improve drop bomb code example --- .../raii/drop_bomb.md | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/idiomatic/leveraging-the-type-system/raii/drop_bomb.md b/src/idiomatic/leveraging-the-type-system/raii/drop_bomb.md index 3cea9057..f0a2b547 100644 --- a/src/idiomatic/leveraging-the-type-system/raii/drop_bomb.md +++ b/src/idiomatic/leveraging-the-type-system/raii/drop_bomb.md @@ -22,14 +22,16 @@ impl Transaction { Self { active: true } } - fn commit(mut self) { + fn commit(mut self) -> io::Result<()> { + writeln!(io::stdout(), "COMMIT")?; self.active = false; - // Dropped after this point — no panic + Ok(()) } - fn rollback(mut self) { + fn rollback(mut self) -> io::Result<()> { + writeln!(io::stdout(), "ROLLBACK")?; self.active = false; - // Dropped after this point — no panic + Ok(()) } } @@ -41,14 +43,23 @@ impl Drop for Transaction { } } -fn main() { - // OK: commit defuses the bomb - let tx1 = Transaction::start(); - tx1.commit(); +fn main() -> io::Result<()> { + let tx = Transaction::start(); + + if some_condition() { + tx.commit()?; + } else { + tx.rollback()?; + } // Uncomment to see the panic: // let tx2 = Transaction::start(); - // dropped without commit or rollback → panic + + Ok(()) +} + +fn some_condition() -> bool { + true // change to false to test rollback } ```