1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-08-08 08:22:52 +02:00

improve drop bomb code example

This commit is contained in:
Glen De Cauwsemaecker
2025-08-02 10:59:24 +02:00
parent 4ebb43f663
commit 42a423764e

View File

@ -22,14 +22,16 @@ impl Transaction {
Self { active: true } Self { active: true }
} }
fn commit(mut self) { fn commit(mut self) -> io::Result<()> {
writeln!(io::stdout(), "COMMIT")?;
self.active = false; 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; self.active = false;
// Dropped after this point — no panic Ok(())
} }
} }
@ -41,14 +43,23 @@ impl Drop for Transaction {
} }
} }
fn main() { fn main() -> io::Result<()> {
// OK: commit defuses the bomb let tx = Transaction::start();
let tx1 = Transaction::start();
tx1.commit(); if some_condition() {
tx.commit()?;
} else {
tx.rollback()?;
}
// Uncomment to see the panic: // Uncomment to see the panic:
// let tx2 = Transaction::start(); // let tx2 = Transaction::start();
// dropped without commit or rollback → panic
Ok(())
}
fn some_condition() -> bool {
true // change to false to test rollback
} }
``` ```