162. Pin<P> — The Pointer Type That Says 'This Won't Move'
Self-referential structs are the obvious “this should work but doesn’t” pattern in Rust: a struct that holds a buffer plus a reference into that buffer falls apart the moment it moves and the reference dangles. Pin<P> is the type that says “the pointee is fixed in memory” — and is the reason every async fn future you’ve ever .awaited can keep a pointer to its own local variables.
Why Pin exists at all
Take a String and a slice into it:
| |
You can’t actually build this — Rust won’t let you write a struct that borrows from one of its own fields, because the move that follows construction would invalidate the borrow. Any helper that produces a Mess and returns it by value moves buf into the caller’s stack frame; view would still point at the old location. Disaster.
async fn bodies generate exactly this kind of struct under the hood: an enum of “states,” each carrying the locals live across an .await. If one of those locals is a reference to another local, the future is self-referential. Move it after polling and you’ve hit UB.
What Pin actually does
Pin<P> wraps a pointer — Box<T>, &mut T, Rc<T>, etc. — and downgrades its API. Specifically: you can no longer reach the inner &mut T unless T: Unpin.
Without &mut T, you can’t std::mem::swap or mem::replace to move the value out. That’s the whole guarantee: the value behind a Pin<P> will never move again, except by running its destructor.
| |
For i32 the pinning is theatre — primitives implement Unpin, the marker that says “moving me is fine.” Pin only bites when the inner type is !Unpin.
Where it bites: polling a future
Future::poll takes self: Pin<&mut Self>. The compiler-generated futures from async {} are !Unpin, so you can’t poll them through a plain &mut. You have to pin first.
| |
Box::pin is the easy answer when you need an owned, heap-allocated, pinned future. The allocation is what makes the address stable — Box already promised that.
Stack pinning with pin!
Heap allocation just to poll a future feels heavy, and it is. The pin! macro pins a value on the stack instead: it shadows the binding so you can never get a non-pinned reference to it again.
| |
The trick is that pin! re-binds fut to a Pin<&mut _> that borrows from a hidden, scope-local slot. The original value lives until the end of the block; nothing can sneak in and move it. Stable since Rust 1.68.
Unpin: the escape hatch for ordinary types
Unpin is an auto trait: almost everything implements it automatically. String, Vec<T>, your own struct of plain fields — all Unpin. For those, Pin<&mut T> and &mut T are interchangeable via Pin::new and Pin::into_inner:
| |
This is why most of the time you can pretend Pin doesn’t exist. It only shows teeth when something is deliberately !Unpin — async-generated futures, intrusive linked-list nodes, and any self-referential struct you opt into with PhantomPinned.
When you’ll see it yourself
In day-to-day code you almost never write Pin<P> directly — the pin! macro and Box::pin cover polling, and tokio::pin! or tokio::spawn cover the async runtime case. You’ll meet Pin<&mut Self> in earnest when you:
- Hand-roll a
Future.polltakesPin<&mut Self>, so any state machine you implement by hand has to thread it through. - Write a self-referential struct. Stick a
PhantomPinnedfield in, and from then on the only way to use the type is through aPin. - Build a custom executor. Pinning the futures the executor stores is exactly the invariant the
Futuretrait is asking you for.
The mental model that sticks: Pin<P> doesn’t pin the pointer — it pins what the pointer points at. The pointer can move, be copied, be passed around; the value under it has promised to stay where it was first pinned, all the way until Drop. That’s the contract the async machinery is built on, and the reason it’s safe to keep an .await point inside a function call hundreds of frames deep.