Sub topic 11
Pinning in practice: Box::pin, pin!, and Pin::as_mut
This chapter assumes you know what Pin and Unpin mean, as covered in the previous chapters. Here you will learn the three tools you use to pin futures in everyday code.
Why you need to pin by hand
Future::poll takes self: Pin<&mut Self>. A plain future value is not pinned, so you must wrap it before you can poll it. There are two common ways, depending on where the future lives.
| Tool | Where the future lives | Result type | Allocates? |
|---|---|---|---|
| `Box::pin(fut)` | Heap | `Pin<Box<F>>` | Yes |
| `std::pin::pin!(fut)` | Current stack frame | `Pin<&mut F>` | No |
Pinning on the heap with Box::pin
Box::pin moves the value into a heap allocation and returns a Pin<Box<F>>. Moving the Box afterwards only copies the pointer, so the future itself stays put. The result can be returned from functions and stored in structs.
It also erases the concrete type. Each async block has its own unnameable type, so Pin<Box<dyn Future>> is how you store several of them together.
use std::future::Future;
use std::pin::Pin;
fn boxed(n: u32) -> Pin<Box<dyn Future<Output = u32>>> {
Box::pin(async move { n + 1 })
}Pinning on the stack with pin!
std::pin::pin! takes a future and gives you a Pin<&mut F> that points at a hidden local variable. The original name is gone, so nothing can move the future afterwards. No allocation is needed, but the pinned reference cannot outlive the current scope.
Polling through as_mut
poll consumes its Pin<&mut Self> argument. If you pass your pinned reference directly, you lose it after the first call. Pin::as_mut reborrows it and returns a fresh Pin<&mut F>, so the original remains usable in a loop.
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(),
}
}
}Here pin!(fut) shadows the argument. Each loop iteration calls fut.as_mut(), which gives poll a short-lived Pin<&mut F> and keeps fut valid for the next pass.
Common errors
the trait Unpin is not implemented: you calledpollor.await-like helpers on a future that is not pinned. Wrap it withBox::pinorpin!.use of moved valueon aPin<&mut F>: you passed it topolldirectly. Useas_mut().borrowed value does not live long enough: apin!reference escaped its scope. UseBox::pinif the future must outlive the function.
Exercise
Why does the loop in block_on call fut.as_mut().poll(&mut cx) instead of fut.poll(&mut cx)?
Show answer
poll takes its Pin<&mut Self> by value, so passing fut directly would move it and make the second loop iteration fail to compile. as_mut() makes a temporary reborrow, which poll consumes while fut stays available.
Exercise
You need a Vec holding 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. The element type is Pin<Box<dyn Future<Output = u32>>>, because each async block has a different concrete type and boxing erases it.