Know what happens when work stops.
Treat cancellation and spawned tasks as part of the API contract.
01 Understand the contract
Pin constrains movement of a value that must remain at a stable memory location. Some futures need this because their state can contain references related to their own storage. Box::pin safely creates an owned pinned allocation. Dropping a future cancels that future’s remaining work, but does not roll back side effects it already performed. Dropping a Tokio JoinHandle detaches the spawned task rather than cancelling it. Build cancellation-safe boundaries with explicit task ownership, timeouts, and cleanup rather than assuming everything stops together.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
use std::{future::Future, pin::Pin};
async fn answer() -> u32 {
42
}
fn hold(_: Pin<Box<dyn Future<Output = u32>>>) {}
fn main() {
let work: Pin<Box<dyn Future<Output = u32>>> = Box::pin(answer());
hold(work);
println!("pinned future created, not executed");
}pinned future created, not executed
- 1
Box::pin provides a stable owned location.
- 2
The trait object erases the concrete future type.
- 3
No polling happens in hold, so the future is dropped without executing.
cargo run -p lesson_pin_cancellation03 Mind the boundary
04 Your next build
Write a generic function accepting an owned Future without polling it, and pass an async block.
Reveal one possible solution +
use std::future::Future;
fn discard<F: Future<Output = u32>>(_: F) {}
fn main() {
discard(async { 7_u32 });
}05 Check your reasoning
Does dropping a future undo effects already completed?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.