Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures

Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.

~4 min readRust
#Rust#Async#Memory Safety
3D illustration of a self-referential struct anchored in heap memory by a Pin lock

Quick Summary

Pin solves one problem: some types contain pointers to their own fields, so moving the value after those pointers are set leaves them dangling. Pin<P> wraps a pointer and promises the pointee will not be moved again — not by safe code, not by Vec reallocation, not by swapping two values.

Unpin is the opt-out. Almost every type is Unpin, which means "moving is harmless"; for those types Pin is a no-op wrapper and safe code can take the value back out. A type becomes !Unpin only when it explicitly says so, usually by containing a PhantomPinned marker — or by being the compiler-generated state machine of an async fn, which is always !Unpin.

The practical consequence: async fn returns a future that must be pinned before polling, and any API that stores or returns futures has to decide whether to pin them (Pin<Box<dyn Future>>) or require Unpin from the caller. Getting this wrong does not produce a compile error — it produces a future that resumes from a corrupted state.

Basic Syntax & Signature

rust
use std::pin::{pin, Pin}; use std::marker::PhantomPinned; // Most types are Unpin: Pin adds nothing. fn needs_unpin<T: Unpin>(value: T) -> T { value } fn main() { let mut n = 5; let p: Pin<&mut i32> = Pin::new(&mut n); // requires i32: Unpin *p = 6; assert_eq!(n, 6); // !Unpin: a type that opts out of moving. struct Tracked { value: u32, _pin: PhantomPinned, // makes Tracked !Unpin } let tracked = Tracked { value: 1, _pin: PhantomPinned }; // Pin::new(&mut tracked) would not compile: Tracked is !Unpin. // Box::pin moves the value to the heap, then pins it there. let boxed: Pin<Box<Tracked>> = Box::pin(Tracked { value: 2, _pin: PhantomPinned }); assert_eq!(boxed.value, 2); // pin! pins a value on the stack for the rest of the scope. let mut tracked2 = Tracked { value: 3, _pin: PhantomPinned }; let pinned: Pin<&mut Tracked> = pin!(tracked2); // tracked2 can no longer be moved, but its fields can still be read. assert_eq!(pinned.value, 3); assert_eq!(needs_unpin(7), 7); }

The API surface that matters:

rust
impl<P: Deref> Pin<P> { pub unsafe fn new_unchecked(pointer: P) -> Self; pub fn as_ref(&self) -> Pin<&P::Target>; pub fn into_inner(self) -> P where P::Target: Unpin; } impl<'a, T: ?Sized> Pin<&'a mut T> { pub fn new(pointer: &'a mut T) -> Self where T: Unpin; pub fn get_mut(self) -> &'a mut T where T: Unpin; pub unsafe fn get_unchecked_mut(self) -> &'a mut T; pub unsafe fn map_unchecked_mut<U, F: FnOnce(&mut T) -> &mut U>(self, f: F) -> Pin<&'a mut U>; } impl<T> Box<T> { pub fn pin(x: T) -> Pin<Box<T>>; } pub fn pin<T>(value: T) -> Pin<&mut T>; // std::pin::pin!, stable since 1.68

Key Comparison Table

Value TPin<Box<T>>Pin<&mut T>
Where it livesStack or inlineHeapWherever the reference points
Can move after pinningYes (if not pinned)No, the Box owns itNo
Can read fieldsYesYes, through DerefYes, through Deref
Can mutate fieldsYesOnly if T: Unpin, or via unsafe projectionOnly if T: Unpin, or via unsafe projection
Typical useOrdinary dataStored, boxed futuresTemporary polling
Trait / typeMeaningImplemented by
UnpinMoving is safe even when pinnedAlmost everything; auto trait
!UnpinMust not move once pinnedTypes with PhantomPinned, async fn futures, tokio futures
PhantomPinnedZero-sized marker that removes UnpinAdded as a field
Pin<P>Pointer wrapper asserting no-moveConstructed by Box::pin, pin!, new_unchecked
DerefMut on Pin<&mut T>Only exists when T: UnpinSo *pin = value fails for !Unpin

Practical Edge Cases & Deep Dives

1. Why Pin exists: a self-referential struct

rust
use std::marker::PhantomPinned; use std::pin::Pin; struct SelfRef { data: String, // Points at `data` inside the same struct. ptr: *const String, _pin: PhantomPinned, } impl SelfRef { fn new(data: &str) -> Pin<Box<Self>> { let mut boxed = Box::pin(SelfRef { data: data.to_string(), ptr: std::ptr::null(), _pin: PhantomPinned, }); // SAFETY: `boxed` is pinned, so `data` will not move for as long as // the box lives; we write the pointer exactly once, before releasing // it to safe code. unsafe { let this = Pin::as_mut(&mut boxed).get_unchecked_mut(); this.ptr = &this.data as *const String; } boxed } fn data_via_ptr(&self) -> &str { // SAFETY: `ptr` was set to `&self.data` and the struct has not moved // since, which is the invariant `Pin<Box<Self>>` enforces. unsafe { (*self.ptr).as_str() } } } fn main() { let s = SelfRef::new("hello pin"); assert_eq!(s.data_via_ptr(), "hello pin"); assert_eq!(s.data.as_str(), "hello pin"); }

The pointer is set after the value is already on the heap and pinned; a plain Box<Self> would allow let moved = *boxed; and the pointer would then refer to freed memory. PhantomPinned is what prevents Pin::new from being callable, forcing callers to use Box::pin or pin!.

2. Polling a future correctly

rust
use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; struct Countdown { remaining: u32 } impl Future for Countdown { type Output = &'static str; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { // Countdown is Unpin-like: every field is plain data, so we can take // a mutable reference out of the pin without breaking any invariant. let this = self.get_mut(); // requires Self: Unpin if this.remaining == 0 { return Poll::Ready("done"); } this.remaining -= 1; cx.waker().wake_by_ref(); Poll::Pending } } impl Unpin for Countdown {} fn main() { let mut f = Countdown { remaining: 2 }; let mut f = unsafe { Pin::new_unchecked(&mut f) }; let waker = futures::task::noop_waker(); let mut cx = Context::from_waker(&waker); assert!(matches!(f.as_mut().poll(&mut cx), Poll::Pending)); assert!(matches!(f.as_mut().poll(&mut cx), Poll::Pending)); assert!(matches!(f.as_mut().poll(&mut cx), Poll::Ready("done"))); }

The signature self: Pin<&mut Self> is what tells callers the future may be self-referential. A hand-written future whose fields are all plain data can declare impl Unpin and use get_mut freely; the compiler-generated futures from async fn cannot, because their state machine stores references to local variables across .await.

3. pin! on the stack versus Box::pin

rust
use std::pin::pin; async fn work() -> u32 { let a = 1; let b = async { a + 1 }.await; b * 2 } fn main() { // Stack-pinned: no allocation, valid until the end of the scope. { let fut = work(); let mut pinned = pin!(fut); let waker = futures::task::noop_waker(); let mut cx = std::task::Context::from_waker(&waker); let _ = std::future::Future::poll(pinned.as_mut(), &mut cx); } // Heap-pinned: can be stored, returned, or put in a collection. let boxed = Box::pin(work()); assert_eq!(std::mem::size_of_val(&boxed), 8); }

pin! borrows the local for the whole block, so the value cannot be moved afterwards — which is exactly the guarantee needed, without the allocation. Box::pin is the choice when the future must outlive the current scope or be stored in a struct field, since Pin<&mut T> has a lifetime tied to its borrow.

4. Projecting a pinned struct to one pinned field

rust
use std::marker::PhantomPinned; use std::pin::Pin; use std::task::{Context, Poll}; struct Outer { label: String, inner: Inner, _pin: PhantomPinned, } struct Inner { polls: u32, _pin: PhantomPinned } impl Outer { fn new(label: &str) -> Pin<Box<Self>> { Box::pin(Outer { label: label.to_string(), inner: Inner { polls: 0, _pin: PhantomPinned }, _pin: PhantomPinned, }) } // Safe projection: the returned Pin borrows the same memory. fn inner_mut(self: Pin<&mut Self>) -> Pin<&mut Inner> { // SAFETY: `inner` is structurally pinned — we never move it out and // never hand out a plain &mut to it elsewhere. unsafe { self.map_unchecked_mut(|o| &mut o.inner) } } fn label(&self) -> &str { &self.label } } impl std::future::Future for Inner { type Output = u32; fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<u32> { // SAFETY: all fields are plain data; moving `polls` is harmless. let this = unsafe { self.get_unchecked_mut() }; this.polls += 1; Poll::Ready(this.polls) } } fn main() { let mut outer = Outer::new("job"); assert_eq!(outer.label(), "job"); let waker = futures::task::noop_waker(); let mut cx = Context::from_waker(&waker); let polled = std::future::Future::poll(outer.as_mut().inner_mut(), &mut cx); assert_eq!(polled, Poll::Ready(1)); }

map_unchecked_mut is where "structural pinning" is decided. Once a field is projected as pinned, the type must never move that field, never expose &mut Field, and never implement Drop in a way that moves it out — the compiler cannot check any of these, which is why pin-project-lite generates the projection plus the correct Drop guard instead.

5. Futures in collections and dyn Future

rust
use std::pin::Pin; type BoxFuture<'a, T> = Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>; async fn one() -> u32 { 1 } async fn two() -> u32 { 2 } fn main() { // A Vec cannot hold two different anonymous future types... unless boxed. let mut tasks: Vec<BoxFuture<'static, u32>> = Vec::new(); tasks.push(Box::pin(one())); tasks.push(Box::pin(two())); assert_eq!(tasks.len(), 2); // Polling them requires a runtime; the type-level story is the point: // `Pin<Box<...>>` is the only way to erase two distinct future types // into one collection while keeping the no-move guarantee. let _ = &mut tasks; }

The 'static bound comes from owning the future: a boxed future that borrows locals cannot outlive them. In async code this is why async move blocks and 'static tasks are the norm, and why futures::future::BoxFuture<'a, T> carries an explicit lifetime.

6. Unpin bounds in generic async code

rust
use std::future::Future; // Requires the future to be movable: the compiler box-pins it for us. async fn call_unpin<F: Future<Output = u8> + Unpin>(f: F) -> u8 { f.await } // Accepts any future by pinning it internally: no Unpin bound needed. async fn call_any<F: Future<Output = u8>>(f: F) -> u8 { // The `.await` desugars to a pinned poll of `f` in the local state machine. f.await } fn main() { let fut1 = async { 1u8 }; let fut2 = async { 2u8 }; let _ = call_any(fut1); let _ = call_any(fut2); // call_unpin(fut1) would fail: async blocks are !Unpin. }

Adding Unpin to a public async API narrows the set of callers for no benefit in most cases, because the caller's async fn already pins whatever it awaits. Unpin bounds belong on APIs that must move the future after creating it, such as a custom executor that stores futures inline in a slab without pinning.

Common Compilation/Runtime Mistakes

Error / symptomCauseFix
E0277: 'T: Unpin' is not satisfied on Pin::newType is !UnpinBox::pin, pin!, or new_unchecked with a real argument
cannot move out of ... which is behind a PinAttempting to take the valueOnly Unpin types can be moved out; otherwise keep the pin
cannot borrow as mutable through Pin<&mut T>DerefMut requires Unpinget_unchecked_mut with a safety comment, or a projection crate
The future stops making progressA field was moved out of a pinned structNever move structurally pinned fields
Address changes reported by Miri after pinningSelf-referential pointer invalidatedPin before setting the pointer, as in SelfRef::new
Pin<&mut T> outlives the valueStack value dropped while pinned reference livesBox::pin, or scope the pin carefully
Box<dyn Future> cannot be polledpoll needs Pin<&mut Self>Store Pin<Box<dyn Future>>
Unpin bound breaks callersasync fn futures are !UnpinRemove the bound; rely on the caller's pinning
A Vec<BoxFuture> needs 'staticBoxed future cannot borrow localsasync move, or an explicit 'a
Soundness lint on custom projectionmap_unchecked_mut promises structural pinningUse pin-project-lite

Two habits keep this tractable. First, do not add Unpin to signatures unless something actually moves the value after pinning — it is the most common cause of "this compiles for my test but not for my caller". Second, treat every get_unchecked_mut as a written assertion that no field needs a stable address; if even one field might, project with pin-project-lite and let the macro generate the Drop guard that prevents moving out of a pinned value.

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.