#async #drop

async-drop

simple async drop

2 releases

Uses new Rust 2024

new 0.1.2 Mar 9, 2026
0.1.1 Mar 5, 2026

#946 in Asynchronous

MIT license

8KB
94 lines

Async drop support for Rust.

This crate provides AsyncDrop, a trait for types that need to perform asynchronous cleanup, and Dropper, a wrapper that automatically runs the async cleanup when the value is dropped.

Example

use async_drop::{AsyncDrop, AsyncDropFuture, Dropper};

struct DbConnection;

impl AsyncDrop for DbConnection {
    fn async_drop(&mut self) -> AsyncDropFuture<'_> {
        Box::pin(async {
            // Close the connection gracefully...
            Ok(())
        })
    }
}

let conn = Dropper::new(DbConnection);
// Use `conn` as if it were a `DbConnection` (via Deref).
// When `conn` goes out of scope, `async_drop` runs automatically.

Async Drop

Inspired by async-dropper

Adjustments

  • Removed async_trait crate dependency
  • Types don't have to implement Default
  • Dropper's drop will wait until async_drop completes
  • Only compatible with the tokio runtime (for now)

Usage

struct Thing;

impl AsyncDrop for Thing {
    fn async_drop(&mut self) -> AsyncDropFuture<'_> {
        Box::pin(async {
            tokio::time::sleep(Duration::from_secs(3)).await;
            println!("dropped");
            Ok(())
        })
    }
}

#[tokio::main]
async fn main() {
    {
        let _thing = Dropper::new(Thing);
        println!("dropping...");
    } // `_thing` is dropped here, but before that happens `async_drop()` will run to completion
}

Examples

See test and example directories

Dependencies

~1.7–2.5MB
~35K SLoC