What are Pin<T> and Unpin in Rust async programming?
Answer
Pin<T> is a wrapper type that guarantees an object will not be moved in memory after it has been pinned. This is necessary for self-referential types — most commonly the state machines generated by async functions with multiple .await points. These state machines contain references to their own fields; if the state machine were moved in memory, those self-references would become dangling pointers. Pin prevents movement by making the safe API inaccessible unless the inner type implements Unpin. Unpin is a marker trait (auto-implemented for most types) that says "it is safe to move this type even when pinned." For async code, the Future trait requires fn poll(self: Pin<&mut Self>, ...) — the pin ensures the future's state machine is not moved between polls. Use Box::pin() or pin_mut!() to pin a value.
Previous
What are zero-cost abstractions and monomorphization in Rust?
Next
How does the async runtime work internally in Rust (Waker, Poll, Executor)?
More Rust Questions
View all →- Advanced What are zero-cost abstractions and monomorphization in Rust?
- Advanced How does the async runtime work internally in Rust (Waker, Poll, Executor)?
- Advanced What are the rules for writing correct unsafe Rust?
- Advanced How does Rust FFI (Foreign Function Interface) work with C?
- Advanced What is procedural macro metaprogramming with syn, quote, and proc_macro2?