What Is Pin and Why Does Async Rust Need It?

Pin is a smart pointer that prevents memory movement, ensuring async Rust futures remain safe when paused and resumed.

Pin is a smart pointer that prevents a value from being moved in memory, which is required for async Rust to safely resume futures that contain self-referential data. Without Pin, resuming a future could invalidate internal pointers, leading to undefined behavior. You use Pin by wrapping a future in Pin::new_unchecked (unsafe) or Box::pin (safe) before awaiting it.

use std::pin::Pin;
use std::future::Future;

fn main() {
    let future = async { 42 };
    let pinned: Pin<Box<dyn Future<Output = i32> + '_>> = Box::pin(future);
    // pinned cannot be moved, ensuring safety during async execution
}