skip to content

In Rust, what is the difference between pinning a future with `std::pin::pin!` and with `Box::pin`, and when do you use each?

level: juniorimportance: should knowfreq 40%

answer

  1. where the future lives
  2. a local versus a heap allocation
  3. can the pin leave the scope
  4. returning different async blocks

basics

~20 s

pin! (stable since Rust 1.68) pins a future in the current scope's local storage and returns Pin<&mut F>, with no allocation but no escape. Box::pin moves it to the heap and returns an owned Pin<Box<F>> you can return or store.

solid answer

~40 s

Both safely pin a `!Unpin` future so it can be polled or passed where `Unpin` is required. `std::pin::pin!(fut)`, stable since Rust 1.68, moves the future into a hidden local of the enclosing block and yields `Pin<&mut F>`: it costs no allocation and works in `no_std`, but the pin borrows that local, so it cannot be returned or outlive the scope. `Box::pin(fut)` allocates once and yields `Pin<Box<F>>`, which owns the future and can be returned, stored in a struct or a `Vec`, or erased to `Pin<Box<dyn Future<Output = T> + Send>>` so that one function can return different async blocks. Use `pin!` for a future you finish polling in the same function, and `Box::pin` when it has to travel. Since 1.97, `pin!` on a `&mut F` gives `Pin<&mut &mut F>` and no longer deref-coerces.

code

rust · 25 lines
rust
use futures::executor::block_on;
use std::future::Future;
use std::pin::{Pin, pin};

type FrameFuture = Pin<Box<dyn Future<Output = usize> + Send>>;

// Two different async blocks have two different types, so the function
// returns one boxed, pinned trait object; Box::pin pins each on the heap.
fn parser_for(version: u8, input: Vec<u8>) -> FrameFuture {
    if version == 1 {
        Box::pin(async move { input.len() })
    } else {
        Box::pin(async move { input.iter().filter(|b| **b != 0).count() })
    }
}

fn main() {
    let mut queue: Vec<FrameFuture> = vec![parser_for(1, vec![1, 0, 2]), parser_for(2, vec![1, 0, 2])];
    let last = queue.pop().unwrap(); // moving a Pin<Box<_>> moves only the pointer
    println!("{}", block_on(last));

    // A future consumed in this scope: pin it on the stack, no allocation.
    let local = pin!(async { 40 + 2 });
    println!("{}", block_on(local));
}

go deeper

for a junior

Remember the two constructors: pin! for a future used right here, Box::pin when you must return or store it, including Pin<Box<dyn Future>> returns.

for a middle

Explain that pin! moves the value into an unnameable local and returns Pin<&mut F>, why that cannot escape, and why Pin<Box<F>> is Unpin and freely movable.

for a senior

Weigh the allocation and dynamic dispatch of boxed futures on hot paths, keep pin! for no_std, and know the 1.97 change to pin! on &mut arguments.

for a principal

Set the boxing policy for public APIs: concrete impl Future returns keep callers allocation-free, while boxed dyn futures buy uniform types and simpler signatures.

## The two everyday ways to pin A future produced by `async fn` or an `async` block is `!Unpin`, so before anything can poll it through `Future::poll(self: Pin<&mut Self>, ...)`, or pass it to an API that demands `Unpin`, it must be **pinned**: placed somewhere it will not move until it is dropped, behind a `Pin` pointer. `.await` does this for you inside an async body. When you need the pin yourself, safe Rust's two everyday constructors for a `!Unpin` value are below; `Rc::pin` and `Arc::pin` exist too, and `Pin::new` works only for `Unpin` values. | | `std::pin::pin!(fut)` | `Box::pin(fut)` | |---|---|---| | Result type | `Pin<&mut F>` | `Pin<Box<F>>` | | Where `F` lives | a hidden local of the enclosing block | a new heap allocation | | Cost | none beyond the move | one allocation, freed on drop | | Can be returned or stored | no, it borrows a local | yes, it owns the future | | Works in `#![no_std]` without an allocator | yes | no | | Stable since | Rust 1.68 | Rust 1.33 | ## `pin!`: pinning in place `pin!` moves its argument into a local that nothing outside the macro can name, then hands out a `Pin<&mut F>` to it. Because the local cannot be named, it cannot be moved again, which is what makes the macro safe. The documentation calls it the main non-`unsafe`, `no_std`-compatible way to pin and notes it is likely to be cheaper than a heap allocation. The price is scope. The resulting reference borrows that local, so returning it fails: `fn make() -> Pin<&'static mut dyn Future<Output = u32>> { pin!(async { 7 }) }` is rejected with E0515, "cannot return value referencing temporary value". The docs' advice is to pass futures around **unpinned** and pin them with `pin!` at the point where they are consumed, for example right before a manual poll loop or a `select`. Inside an `async` block, "local" means the enclosing future's own state rather than the thread's stack, which is fine: that future is itself pinned while it runs. ## `Box::pin`: pinning on the heap `Box::pin(fut)` allocates, moves the future into the allocation, and returns `Pin<Box<F>>`. The future stays at its heap address while the box itself can move freely: `Pin<Box<F>>` is `Unpin` and implements `Future`, so it can be awaited, polled with `as_mut()`, pushed into a `Vec` or returned. Typical uses: - **Returning one of several async blocks.** Each `async` block has its own anonymous type, so a function choosing between two of them returns `Pin<Box<dyn Future<Output = T> + Send>>`, building each arm with `Box::pin`. The futures crate names that type `BoxFuture<'a, T>` and offers `FutureExt::boxed` to build it. - **Storing futures** in a struct field or a collection whose element type must be one concrete type. - **Keeping a future** across function boundaries, such as a pending request held by a connection object. Recursive `async fn`s also need boxing; the material on async functions covers that case and its error. ## Common mistakes - **Pinning a reference instead of the future.** `pin!(&mut fut)` pins the reference; for an async future that does not give you something you can await (see the release note below). - **Pinning inside a loop.** Creating and pinning the future inside a loop body starts a new future each iteration; create and pin it once before the loop and reuse it with `as_mut()`. - **Reaching for `Box::new`.** A plain `Box<F>` is not pinned; its `Future` impl requires `F: Unpin`, so it does not help an async future. `Box::pin`, or `Box::into_pin` on an existing box, is what produces `Pin<Box<F>>`. ## Choosing between them 1. Future created and fully polled in the same function or async block: `pin!`. 2. Future returned, stored, or kept in a heterogeneous collection: `Box::pin`. 3. `no_std` without an allocator: `pin!` is the main safe option. 4. Hot paths that create many short-lived futures: prefer `pin!` to avoid one allocation each. ## A release note worth knowing `pin!` takes its argument by value and does not coerce it. Since Rust 1.97, `pin!(r)` where `r: &mut F` always produces `Pin<&mut &mut F>`; releases from 1.88 sometimes coerced it to `Pin<&mut F>`, which the 1.97 notes call incorrect and removed for soundness. `Pin<&mut &mut F>` is a `Future` only when `F: Unpin`, so for an async future pin the future itself, `pin!(fut)`, not a reference to it.

  • Why can't you return the `Pin<&mut F>` that `pin!` produced?
    `pin!` stores the future in a hidden local of the enclosing block and returns a reference to it, so the pin borrows that local. Returning it would outlive the storage, and rustc rejects it, for instance with E0515 "cannot return value referencing temporary value". Return the future unpinned and let the caller pin it, or return `Pin<Box<F>>`.
  • Is a `Pin<Box<dyn Future>>` slower to poll than a future pinned with `pin!`?
    Polling goes through a vtable call for the `dyn` version, and creating it costs one heap allocation. For a handful of long-lived futures that is negligible; for many short-lived futures on a hot path, `pin!` with a concrete type avoids both costs.

  • Says pin! allocates the future on the heap.
  • Returns the Pin<&mut F> from pin! out of a function.
  • Thinks Box::new(fut) pins the future the same way Box::pin does.
  • Claims Box::pin is the only safe way to pin a !Unpin future.
  • Writes pin!(&mut fut) and expects a pinned future it can await.

Assumes Rust 1.99; pin! is stable since 1.68 and since 1.97 no longer deref-coerces a &mut F argument.