Sub topic 9
Pin: promising a value will not move
This chapter assumes you know Rust ownership and borrowing, traits and generics, and the Future trait with poll. You should also know that an async block compiles to a state machine, and that such a state machine can hold references into itself. Here we look at how Pin stops a value from moving. The next chapter covers Unpin and PhantomPinned in more detail.
The problem in one paragraph
In safe Rust, any value you own can be moved. You can pass it by value, return it, or swap it with std::mem::swap or std::mem::replace through a &mut T. A move copies the bytes to a new address. If those bytes contain a pointer to the value's own old address, the pointer now dangles. A self-referential future has exactly this shape. poll must therefore be callable only when the future is guaranteed to stay at its current address.
What Pin is
Pin<P> is a thin wrapper around a pointer type P, such as &mut T, Box<T>, or Rc<T>. It does not change the pointer's layout and it does nothing at runtime. It is a type-level marker. While a value sits behind a Pin, safe code cannot get a &mut T to it, unless T opts out of the guarantee by implementing Unpin. Without a &mut T, safe code cannot call mem::swap or mem::replace on it.
The guarantee the pointee gets is this: if T is !Unpin, then once it is pinned, it stays at the same memory address until it is dropped. That includes the memory not being reused before drop runs. Pinning is permanent for that value, and unpinning later is not allowed.
This is why the signature is fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>). The executor must prove the future is pinned before it can poll it. The future's own code can then rely on its address not changing between polls.
Three points follow from this:
Pinpins the pointee, not the pointer. You can move aPin<Box<T>>freely, because only the box pointer moves and the heap data stays put.Pin<&mut T>has the same pinning effect asPin<Box<T>>, but only for the lifetime of the borrow, and the owner ofTis responsible for not moving it afterward.- For types that are
Unpin, which is almost every type you write,Pinhas no effect. Those types may be moved even while "pinned".
Getting a Pin
In practice you use these three safe options. Box::pin allocates, which makes it simple and lets you return the future. pin! is free of allocation but ties the pinned value to the current scope. Pin::new is only for Unpin targets, which is why it is safe: the guarantee is vacuous for them.
Pin::new_unchecked is unsafe because the compiler cannot verify your promise. You must ensure the value is never moved or invalidated before it is dropped, even through other code paths.
What you can do with a Pin
| Operation | Requires | Result |
|---|---|---|
| `*pin` / method calls (`Deref`) | nothing | shared access, `&T` |
| `*pin = ...`, `DerefMut` | `T: Unpin` | mutable access, `&mut T` |
| `Pin::get_mut` | `T: Unpin` | `&mut T` |
| `Pin::get_unchecked_mut` | `unsafe`, you promise not to move | `&mut T` |
| `Pin::as_mut` | nothing | reborrow as `Pin<&mut T>` |
| `Pin::set` | `T: Sized` | overwrite the pointee in place (drops the old value) |
Shared access is always safe. You cannot move out of a &T, so reading cannot break the guarantee. Mutable access is the dangerous operation, so it is gated on Unpin.
Example: pinning an Unpin value
use std::pin::Pin;
fn main() {
let mut value = 5;
let mut pinned: Pin<&mut i32> = Pin::new(&mut value);
*pinned += 1; // DerefMut works because i32 is Unpin
println!("{}", *pinned); // 6
pinned.set(10);
println!("{}", *pinned); // 10
}Because i32 is Unpin, Pin::new is safe and the pin imposes no restrictions.
Example: a value that must stay put
use std::marker::PhantomPinned;
use std::pin::Pin;
struct Anchored {
counter: u32,
_pin: PhantomPinned,
}
impl Anchored {
fn bump(self: Pin<&mut Self>) {
// Safe because we only change a field and never move the struct.
let this = unsafe { self.get_unchecked_mut() };
this.counter += 1;
}
}
fn main() {
let mut boxed = Box::pin(Anchored {
counter: 0,
_pin: PhantomPinned,
});
let before = &*boxed as *const Anchored;
boxed.as_mut().bump();
boxed.as_mut().bump();
let after = &*boxed as *const Anchored;
println!("counter = {}, same address = {}", boxed.counter, before == after);
}This prints counter = 2, same address = true. PhantomPinned makes Anchored !Unpin. As a result, Pin::new(&mut anchored) would not compile, and neither would boxed.counter += 1 through DerefMut. The only way to get &mut Anchored is the unsafe call inside bump, where we take responsibility.
Why `as_mut` exists
Methods that take self: Pin<&mut Self> consume the pin. Pin<&mut T> is not Copy, and unlike a plain &mut T the compiler does not reborrow it implicitly in every position. If you call poll twice in a loop with the same Pin<&mut F>, the second call fails with a use-of-moved-value error. The fix is fut.as_mut().poll(cx), which creates a short-lived Pin<&mut F> from the original and leaves the original usable. You saw this in the block_on loop, which calls fut.as_mut().poll(&mut cx) on each iteration.
Edge cases and common errors
Pindoes not prevent moving the container. If a struct has a pinned field, moving the struct moves the field. Pinning only holds when the struct itself is behind aPin.- Error
the trait Unpin is not implemented. You calledPin::new,get_mut, or usedDerefMuton a!Unpinvalue. This is the compiler stopping you. Pin it withBox::pinorpin!, and if you need mutation, use a method that takesPin<&mut Self>. pin!borrows from its scope. The returnedPin<&mut T>cannot outlive the enclosing block. If you need to return the future, useBox::pin.- Pinned values must be dropped, not forgotten. The guarantee covers the period until
dropruns. Unsafe code that frees or reuses the memory without dropping breaks it. - Futures can be moved before the first poll. The compiler-generated state machine only becomes self-referential after it has run to its first
.await. Pinning is still required to callpoll, so the type system enforces the rule from the start.
Summary of the model
- A move changes an address, and self-references cannot follow it.
Pin<P>takes away safe&mut Taccess for!Unpintargets, so safe code cannot move them.polltakesPin<&mut Self>, so a future can rely on a fixed address between polls.- You get a pin with
Box::pin,pin!, orPin::newforUnpintypes. You useas_mutto poll repeatedly.
Exercise
A loop calls fut.poll(cx) twice on a fut: Pin<&mut F> and the compiler reports a use of a moved value on the second call. What is the cause, and what is the fix? Also, why does Pin::new(&mut x) compile for an i32 but not for a type containing PhantomPinned?
Show answer
poll takes self: Pin<&mut Self> by value, and Pin<&mut F> is not Copy, so the first call consumes fut. Call fut.as_mut().poll(cx) instead, which reborrows a fresh Pin<&mut F> each time. Pin::new requires Target: Unpin. i32 is Unpin, so the pin guarantee is vacuous and the call is safe. A type with PhantomPinned is !Unpin, so Pin::new would let safe code later obtain &mut T and move the value. Use Box::pin or pin! for it.