Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ ASYNC & SYSTEM BOUNDARIES
BUILD NOTE 46 / 53

Know what happens when work stops.

Treat cancellation and spawned tasks as part of the API contract.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

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.

lessons/pin-cancellation/src/main.rs
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");
}
↳ EXPECTED OUTPUT
pinned future created, not executed
  1. 1

    Box::pin provides a stable owned location.

  2. 2

    The trait object erases the concrete future type.

  3. 3

    No polling happens in hold, so the future is dropped without executing.

From the extracted rust-workbench folder
cargo run -p lesson_pin_cancellation

03 Mind the boundary

04 Your next build

A SMALL MISSION

Write a generic function accepting an owned Future without polling it, and pass an async block.

Reveal one possible solution +
solutions/pin-cancellation/src/main.rs
use std::future::Future;
fn discard<F: Future<Output = u32>>(_: F) {}
fn main() {
    discard(async { 7_u32 });
}

05 Check your reasoning

QUICK SIGNAL CHECK

Does dropping a future undo effects already completed?

ONE MORE CONTRACT YOU CAN EXPLAIN.

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.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.