Pin and Unpin
Quick answer
Pin expresses a promise that a pinned pointee will not be moved or invalidated before the end of its pinned lifetime, unless its type permits ordinary movement through Unpin.
Distinguish pointer and pointee
Pin<P> wraps a pointer. The pointer handle may move without moving the pointee. Unpin means a type does not rely on pinning restrictions; many ordinary types implement it. Compiler-generated futures may require pinning because their suspended state can depend on stable addresses. Use safe Box::pin or pin! rather than constructing unchecked pins.
fn main() { let pinned = Box::pin(String::from("stable")); let addr = pinned.as_ref().get_ref() as *const String; let moved = pinned; assert_eq!(addr, moved.as_ref().get_ref() as *const String); println!("{}", moved.as_ref().get_ref());}Expected stdout (not executed):
stableOnly the owning pointer handle was moved.
fn main() { let mut p = std::pin::pin!(5u32); *p.as_mut().get_mut() += 1; println!("{}", *p);}Expected stdout (not executed):
6u32 is Unpin, so getting a mutable reference is allowed.
Common mistake
Heap allocation alone is not a pinning guarantee; do not use unsafe projection without a justified invariant.
Try it yourself
Compare the two examples: identify the movable handle and the pointee.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Pin and Unpin — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A Pin<Box<F>> handle is moved to another variable. What is preserved?
Pin and Unpin — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let pinned = Box::pin(String::from("stable")); let addr = pinned.as_ref().get_ref() as *const String; let moved = pinned; assert_eq!(addr, moved.as_ref().get_ref() as *const String); println!("{}", moved.as_ref().get_ref()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Pin and Unpin — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let mut p = std::pin::pin!(5u32); *p.as_mut().get_mut() += 1; println!("{}", *p); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.