Sub topic 11
Pinning in practice: Box::pin, pin!, and Pin::as_mut
This chapter assumes you know what Pin promises, what Unpin means, and why a self-referential future must not move. Here you will learn the three tools you use every day: Box::pin, std::pin::pin!, and Pin::as_mut. You will also learn the errors you are likely to hit.
The problem: poll needs a pinned reference
Future::poll takes self: Pin<&mut Self>. A plain &mut F is not enough. Suppose you have just called an async fn:
async fn add(a: u32, b: u32) -> u32 {
a + b
}
fn main() {
let mut fut = add(1, 2);
// fut.poll(cx) does not compile: poll wants Pin<&mut F>, not &mut F.
let _ = &mut fut;
}You need a Pin<&mut F>, and there are two common ways to get one. You can put the future on the heap with Box::pin. You can also pin it to the stack with pin!. The choice depends on who owns the future and how long it must live.
Box::pin: pin on the heap
Box::pin(value) moves value into a new heap allocation and returns a Pin<Box<T>>. The heap location is stable, so the value stays put even if you move the Box itself.
use std::future::Future;
use std::pin::Pin;
fn boxed(n: u32) -> Pin<Box<dyn Future<Output = u32>>> {
Box::pin(async move { n + 1 })
}Moving a Pin<Box<T>> copies only the pointer. The T stays where it is. That is why Box::pin is the usual answer when you need to:
- Return a future from a function without naming its type.
- Store futures of different concrete types in one collection, as
Pin<Box<dyn Future<Output = u32>>>. - Make a recursive
async fn, which would otherwise have an infinitely sized type. - Hand a future to code that needs ownership and a stable address, such as a task queue.
The cost is one heap allocation per future, plus dynamic dispatch when you erase the type with dyn.
Pin<Box<T>> is itself Unpin
A Box is only a pointer, and moving a pointer never moves the pointee. So Pin<Box<T>> is Unpin even when T is not. This is why you can freely pass boxed futures around, put them in a Vec, or .await them.
pin!: pin on the stack
The std::pin::pin! macro pins a value in the current scope without allocating. It takes a value and gives you a Pin<&mut T>.
use std::future::Future;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};
struct ThreadWaker(Thread);
impl Wake for ThreadWaker {
fn wake(self: Arc<Self>) {
self.0.unpark();
}
}
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
let mut cx = Context::from_waker(&waker);
loop {
match fut.as_mut().poll(&mut cx) {
Poll::Ready(value) => return value,
Poll::Pending => thread::park(),
}
}
}
fn main() {
let answer = block_on(async { 20 + 22 });
println!("{answer}");
}Here pin!(fut) shadows fut with a Pin<&mut F>. The macro moves the original value into a hidden temporary that lives as long as the enclosing scope. Because the original name is gone, nobody can move or reach the value except through the Pin.
Before pin! was stabilized (Rust 1.68), people wrote let mut fut = fut; let mut fut = unsafe { Pin::new_unchecked(&mut fut) };. That was easy to get wrong, because you could still touch the original variable after the pin. The macro closes that hole, so you should not need unsafe for stack pinning.
Limits of stack pinning
A stack-pinned future cannot outlive its scope. You cannot return a Pin<&mut F> from the function that created it, and you cannot send it to another thread's task. If the future must escape the scope, use Box::pin.
| Need | Use |
|---|---|
| Poll a future inside the current function | `pin!` |
| Avoid a heap allocation | `pin!` |
| Return or store the future | `Box::pin` |
| Mix different future types in a collection | `Box::pin` with `dyn Future` |
| Spawn onto a runtime | The runtime pins it for you |
Pin::as_mut: reborrow without giving up the pin
Calling poll consumes its self: Pin<&mut Self>. A Pin<&mut T> is not Copy, so calling fut.poll(cx) directly would move fut and you could not call it again in the loop. Pin::as_mut fixes this. It takes &mut self on the pin and returns a new Pin<&mut T> with a shorter lifetime.
use std::future::Future;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
struct Noop;
impl Wake for Noop {
fn wake(self: Arc<Self>) {}
}
fn main() {
let waker = Waker::from(Arc::new(Noop));
let mut cx = Context::from_waker(&waker);
let mut fut = pin!(async { 7 });
// as_mut reborrows, so `fut` is still usable afterwards.
match fut.as_mut().poll(&mut cx) {
Poll::Ready(v) => println!("ready: {v}"),
Poll::Pending => println!("pending"),
}
}The same method exists on Pin<Box<T>>, where it turns &mut Pin<Box<T>> into Pin<&mut T>. So the loop in block_on works the same whether fut came from pin! or Box::pin.
A common error looks like this:
error[E0382]: use of moved value: `fut`It appears when you write fut.poll(cx) inside a loop. The fix is fut.as_mut().poll(cx).
Pin::new and the Unpin shortcut
If T: Unpin, you can skip all of this and use the safe Pin::new(&mut value). The hand-written CountDown future from earlier chapters is Unpin, because it holds only a u32.
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
struct CountDown(u32);
impl Future for CountDown {
type Output = &'static str;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.0 == 0 {
Poll::Ready("done")
} else {
self.0 -= 1;
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
struct Noop;
impl Wake for Noop {
fn wake(self: Arc<Self>) {}
}
fn main() {
let waker = Waker::from(Arc::new(Noop));
let mut cx = Context::from_waker(&waker);
let mut cd = CountDown(2);
let mut pinned = Pin::new(&mut cd);
assert_eq!(pinned.as_mut().poll(&mut cx), Poll::Pending);
assert_eq!(pinned.as_mut().poll(&mut cx), Poll::Pending);
assert_eq!(pinned.as_mut().poll(&mut cx), Poll::Ready("done"));
}Pin::new requires T: Unpin, so the compiler rejects it for async blocks and for any type containing PhantomPinned. You will see this error:
error[E0277]: `{async block}` cannot be unpinnedWhen you see it, pin the value with pin! or Box::pin instead of looking for a way around the bound.
Common errors and how to read them
- "cannot be unpinned": you called
Pin::new,.poll, or a combinator that needsUnpinon a future that is notUnpin. Pin it first. - "use of moved value" in a loop: add
.as_mut()before eachpoll. - "borrowed value does not live long enough" with
pin!: the pinned future escapes its scope. UseBox::pin. - Selecting on a future by
&mut:&mut FimplementsFutureonly whenF: Unpin. To poll a future in severalselect!iterations, pin it first and pass&mut futof the pinned value. In that case the type isPin<&mut F>, which isUnpin.
use std::future::Future;
use std::pin::pin;
async fn twice<F: Future<Output = u32>>(fut: F) -> u32 {
let mut fut = pin!(fut);
// `&mut fut` is a `&mut Pin<&mut F>`, which is a Future because Pin<&mut F> is Unpin.
let a = (&mut fut).await;
a * 2
}Awaiting &mut fut lets you keep the pinned future in a variable and poll it again later, for example in a retry loop. Do not await a future after it has returned Ready. Most futures panic or misbehave if polled after completion.
Unsafe code stays inside the pin APIs
Pin::new_unchecked and Pin::get_unchecked_mut are unsafe because you promise not to move the value afterwards. Use the safe tools first: Box::pin, pin!, and Pin::new for Unpin types. Write unsafe only when you build a primitive like the SelfRef constructor from earlier, and keep it in one small, documented function.
Exercise
Inside a loop, fut.poll(&mut cx) fails with "use of moved value: fut", where fut is a Pin<&mut F> made by pin!. Why does it fail, and what is the fix?
Show answer
poll takes self: Pin<&mut Self> by value, and Pin<&mut F> is not Copy, so the first call moves fut. Call fut.as_mut().poll(&mut cx). as_mut reborrows and returns a fresh Pin<&mut F>, so fut remains usable on the next iteration.
Exercise
You need a Vec holding futures from two different async blocks that both return u32. Which pinning tool do you use, and what is the element type?
Show answer
Use Box::pin. Each async block has its own unnameable type, so you erase them behind a trait object. The element type is Pin<Box<dyn Future<Output = u32>>>.
Exercise
Why does Pin::new(&mut fut) fail to compile for an async block, but work for CountDown(3)?
Show answer
Pin::new requires T: Unpin. CountDown holds only a u32, so it is Unpin. An async block may hold references into its own state across an .await, so the compiler makes it !Unpin. Pin it with pin! or Box::pin instead.