The Core Dilemma: Move Semantics vs Self-Referential Pointers
In C++ or C, when an object is constructed, it can remain stationary in memory or declare specialized copy/move constructors to adjust pointer offsets when relocated. Rust took an unapologetically different path: all moves are shallow bitwise copies (memcpy). There are no user-defined copy constructors, no move constructors, and zero runtime interception when a struct shifts to another stack slot.
This design enables relentless optimizations, trivial ownership passing into functions, and crystal-clear deallocation mechanics. However, this creates an existential issue for any data structure whose members point to other fields within the same structure.
#[derive(Debug)]struct SelfReferential { value: String, pointer_to_value: *const String, // points to self.value} impl SelfReferential { fn new(text: &str) -> Self { let mut obj = Self { value: String::from(text), pointer_to_value: std::ptr::null(), }; obj.pointer_to_value = &obj.value as *const String; obj }} fn main() { let mut a = SelfReferential::new("Kernel Primitive"); let mut b = SelfReferential::new("Network Buffer"); // DANGER: mem::swap performs a shallow bitwise copy std::mem::swap(&mut a, &mut b); // a.pointer_to_value NOW POINTS INTO b's MEMORY LOCATION! unsafe { println!("Dangling dereference: {}", &*a.pointer_to_value); }}What Actually Breaks When a Future Moves
You might ask: “Why would I ever write a raw self-referential struct with unsafe pointers in modern Rust?” The answer is you usually don’t write it manually — the Rust compiler generates it for you every time you declare an async fn or async block.
When you hold a local variable across an .await boundary, the compiler turns that async function into an anonymous state machine enum. Any local reference created before an await point that is read after that await point becomes a self-referential pointer into the future itself.
value: "Kernel Primitive"
@ 0x7FFA0 ← dangling target
(memcpy) ptr unchanged
value: "Kernel Primitive"
internal_ptr = 0x7FFA0
// still points into Frame A
Notice how internal_ptr still contains 0x7FFA0. If Stack Frame A gets overwritten by a later function call, dereferencing this pointer triggers instant undefined behavior, state corruption, or memory leaks.
The std::pin::Pin Invariant
To prevent this catastrophe, Rust introduced std::pin::Pin<P>. Pin is not a new pointer type — it is a wrapper around existing pointer types (&mut T, Box<T>, Rc<T>) that restricts operations which could move the underlying data.
“If a type T is wrapped in Pin<P<T>> and T does not implement Unpin, it is guaranteed that the pointee at *P will never be moved out of its memory address from the moment it is pinned until its drop logic is executed.”
By depriving caller code of &mut T access (unless T: Unpin), safe Rust prevents std::mem::swap, std::mem::replace, or reassignments. The only way to poll a future is through Future::poll(self: Pin<&mut Self>, cx: &mut Context<'_>).
Why Unpin Is an Auto Trait (and why it matters)
Almost every primitive in Rust (i32, String, Vec<T>, raw pointers) implements the auto trait Unpin. A struct composed entirely of Unpin fields is itself automatically Unpin.
| Operation | T: Unpin (default) | T: !Unpin (PhantomPinned) |
|---|---|---|
| Acquire &mut T | Freely via Pin::into_inner() | Requires unsafe get_unchecked_mut() |
| mem::swap / mem::replace | Allowed | Forbidden by the type system |
| Move the pointee | Always safe | Undefined behavior after pinning |
| Typical members | i32, String, Vec<T> | async fn state, raw self-refs |
Pinning to the Heap (Box::pin) vs Pinning to the Stack (pin_mut!)
There are two primary paradigms to pin a value in memory:
- Heap pinning with
Box::pin— the pointee gets a stable heap address that outlives the current stack frame. The default choice for spawned futures. - Stack pinning with
tokio::pin!/pin_mut!— zero allocation, but the pin is only valid for the enclosing scope, enforced by the borrow checker.
use std::pin::Pin;use std::future::Future;use std::task::{Context, Poll};use std::marker::PhantomPinned; pub struct ZeroCopyStreamEngine { scratchpad: [u8; 4096], staged_ptr: *const u8, // Opt out of the Unpin auto-trait _pin: PhantomPinned,} impl Future for ZeroCopyStreamEngine { type Output = (); fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> { // SAFETY: We never move self from this pinned reference let this = unsafe { self.get_unchecked_mut() }; if this.staged_ptr.is_null() { this.staged_ptr = this.scratchpad.as_ptr(); } Poll::Ready(()) }} pub fn spawn_actor() -> Pin<Box<dyn Future<Output = ()>>> { // Heap pinning ensures the buffer remains at a static heap address Box::pin(ZeroCopyStreamEngine { scratchpad: [0u8; 4096], staged_ptr: std::ptr::null(), _pin: PhantomPinned, })}Drop Safety and Unsafe Invariants
The pinning contract doesn’t end while the struct is executing — it persists until the object is destroyed. If you implement custom Drop logic for a pinned type, you must adhere strictly to these rules:
- Never move the pointee out of
&mut selfinsidedrop—std::mem::takeandOption::takeare both off-limits for!Unpinfields. - Treat
drop(&mut self)as if it receivedPin<&mut Self>; the memory is still pinned during destruction. - If you expose any safe API that hands out
&mut T, you have broken the invariant for every downstream caller.