Dropping Futures in Rust: A Control-Flow Path to Consider

One thing many Rust devs miss (until production): **dropping a Future is a *control-flow path***. In async Rust, cancellation usually happens by **Drop**. That means whenever you use `tokio::select!`, timeouts, or early returns, the “losing” branch gets dropped — and any cleanup/side-effects in `Drop` will run. Why it matters: - If you hold a `MutexGuard`/`RwLockWriteGuard` across an `.await`, cancellation can drop the guard at an unexpected point. - If your type’s `Drop` does I/O, logging, or releases external resources, cancellation becomes observable behavior. - “Looks correct” code can still be **not cancellation-safe**. Practical rule of thumb: - Keep critical sections **small** (don’t hold locks across `.await`). - Treat `Drop` like a finally-block: it will run on *success, error, and cancellation*. - For cleanup, prefer explicit scopes (or `scopeguard`) and design APIs that are cancellation-safe by default. This is one of the reasons Rust async feels so reliable: the compiler helps — but you still need to model cancellation. #rust #softwareengineering #async

To view or add a comment, sign in

Explore content categories