`Pin`
Pin<P> promises that the value behind pointer P will not be moved in memory. Async state machines need that promise because they may borrow their own fields.
Detailed Explanation
Moving a Rust value is normally fine: memcpy the bits, the old location is dead. A self-referential struct — field B points into field A — is wrecked by that memcpy. The generated future for async { let s = String::from("x"); let r = s.as_str(); something(r).await } stores s and r in the same state machine. If you moved the machine after r was set, r would dangle. Pin exists so the executor cannot move it.
Pin<&mut T> is a mutable reference you cannot use to mem::swap the T out, unless T: Unpin. Unpin is an auto trait that means "moving this is always fine". Almost every type is Unpin. The generated async state machines are !Unpin. Box<T> is always Unpin because the box pointer can move while T stays at its heap address; Pin<Box<dyn Future>> is the usual type-erased task.
You pin with pin!(fut) on the stack (the pin macro) or Box::pin(fut) on the heap. Then you poll through the pin. You do not call get_mut on a !Unpin type and move the insides out. That would be the dangling pointer again.
Application code rarely names Pin. You write async/await and spawn. You name it when you store futures in a struct, implement Future by hand, or see Pin<&mut Self> in a poll signature.
When you write Pin: combinators, hand-written futures, intrusive data structures. When you ignore it: normal async functions. When you unsafe a pin projection: you are asserting that a field move is still sound; read the pin module docs first.
Code Examples
use std::pin::pin;
#[tokio::main]
async fn main() {
let fut = async { 40 + 2 };
let mut fut = pin!(fut);
println!("{}", fut.as_mut().await); // prints: 42
}Common Gotchas
Polling a future usually needs it pinned
The `poll` signature takes `Pin<&mut Self>`. Stack-pin with `pin!` or heap-pin with `Box::pin`.
`Unpin` is not a performance flag
It means "this type is safe to move". Forcing `Unpin` on a future with `unsafe` is a soundness bug.
Most of your types are `Unpin`
A `String` can move. The rare `!Unpin` types are futures and a few async primitives.
`Box<T>` pins the `T` in place on the heap
Moving the box moves a pointer. That is why boxed futures are common.