In Rust, what does the `Unpin` auto trait mean, which types implement it, and what does `Pin<&mut T>` restrict when `T: Unpin`?
answer
- a marker about moving
- auto trait, almost everything
- async futures and PhantomPinned opt out
- Pin::new and get_mut need it
basics
~20 sUnpin marks a type that does not rely on staying at one address once pinned. Almost every type gets it automatically; async futures and types holding PhantomPinned do not. For T: Unpin, Pin<&mut T> restricts nothing beyond &mut T.
solid answer
~40 s`Unpin` is an auto trait in `std::marker`: a struct or enum implements it when all its fields do. Primitives, `&T`, `&mut T`, raw pointers, `String` and `Box<T>` for every `T` are `Unpin`. Futures generated from `async fn` and `async` blocks are not, and a type opts out by holding a `std::marker::PhantomPinned` field. The trait only matters together with `Pin`: when the pointee is `Unpin`, `Pin<&mut T>` and `Pin<Box<T>>` behave like `&mut T` and `Box<T>`, with `Pin::new`, `DerefMut`, `get_mut` and `Pin::into_inner` all available, so you can still `mem::replace` the value. When the pointee is `!Unpin`, those methods disappear and it must be pinned with a constructor such as `pin!` or `Box::pin`. `Unpin` changes nothing for a value that is not behind a `Pin`.
code
rust · 23 linesuse std::marker::PhantomPinned;
use std::mem;
use std::pin::{Pin, pin};
struct FrameBuf {
bytes: [u8; 16],
_pin: PhantomPinned, // opts the whole struct out of Unpin
}
fn main() {
// String is Unpin, so Pin<&mut String> restricts nothing.
let mut name = String::from("old");
let mut p = Pin::new(&mut name);
let old = mem::replace(&mut *p, String::from("new")); // DerefMut works
let inner: &mut String = p.get_mut(); // and so does get_mut
inner.push('!');
println!("{old} -> {name}");
// FrameBuf is !Unpin: Pin::new(&mut frame) fails with E0277,
// so it is pinned with pin! and only shared access is safe.
let frame: Pin<&mut FrameBuf> = pin!(FrameBuf { bytes: [0; 16], _pin: PhantomPinned });
println!("{} bytes", frame.bytes.len());
}go deeper
Remember that Unpin is automatic for almost every type and that async futures are the main exception you will meet.
Explain the split in the Pin API: Pin::new, DerefMut, get_mut and into_inner exist only for Unpin pointees, and PhantomPinned opts a type out.
Reason about generic wrappers: a struct is Unpin when its fields are, a safe manual impl Unpin is fine without projections, and an F: Unpin bound pushes boxing onto callers.
Decide where a library's public types sit on the Unpin line, since adding or removing it changes which callers compile and is a visible API commitment.
## What the trait says `Unpin` lives in `std::marker` (defined in `core::marker`) and carries no methods. Its documentation calls a type that implements it **pinning-agnostic**: it does not expose or rely on any pinning guarantee, so a `Pin` pointing at it may offer a fully unrestricted API. Read the other way round, `!Unpin` means "once pinned, this value relies on not moving", which is the case for address-sensitive values such as self-referential futures. Two consequences follow: - **`Unpin` only matters behind a `Pin`.** The `Unpin` docs say it has no consequence at all for non-pinned data: `mem::replace` happily moves a `!Unpin` value through an ordinary `&mut T`. - **It is about the pointee, not the pointer.** For `Pin<Box<T>>`, what counts is whether `T` is `Unpin`; whether `Box` is `Unpin` is irrelevant to the pinning rules. ## Which types implement it `Unpin` is an **auto trait**, like `Send` and `Sync`: the compiler implements it for a struct, enum or closure when every field implements it. | Type | `Unpin`? | Source of the answer | |---|---|---| | `i32`, `bool`, `f32` and other primitives | Yes | listed in the `pin` docs | | `&T`, `&mut T` | Yes, for any `T` | explicit impls in `core::marker` | | `*const T`, `*mut T` | Yes, for any `T` | explicit impls in `core::marker` | | `Box<T>` | Yes, for any `T` | `impl Unpin for Box<T, A>` in `alloc` | | `String` | Yes | named in the `pin` docs | | `Pin<Box<T>>`, `Pin<&mut T>` | Yes, for any `T` | the pointer moves, the pointee does not | | `async fn` and `async` block futures | No | rustc marks them `!Unpin`, even `async { 1 }` | | `PhantomPinned` and any type containing it | No | `impl !Unpin for PhantomPinned` | Because it is an auto trait, a generic wrapper like `struct Timed<F> { inner: F }` is `Unpin` exactly when `F` is. ## What `Pin<&mut T>` allows when `T: Unpin` The `Pin` API splits on that bound: 1. **`Pin::new(ptr)`** exists only when the pointee is `Unpin`. For a `!Unpin` value it fails with E0277; what remains are pinning constructors such as `pin!`, `Box::pin`, `Rc::pin` and `Arc::pin`. 2. **`DerefMut`** is implemented for `Pin<Ptr>` only when the target is `Unpin`, so `&mut *pinned` and method calls taking `&mut self` work. 3. **`Pin::get_mut`** and **`Pin::into_inner`** hand back the plain `&mut T` or pointer, again only for `Unpin` targets. 4. **`Deref`**, **`as_ref`**, **`as_mut`** and **`set`** are available for every target, `Unpin` or not. So for `String`, `let mut p = Pin::new(&mut name); mem::replace(&mut *p, other)` compiles: the `Unpin` docs use exactly this example and note it is possible only because `String` implements `Unpin`. ## Opting out, and opting in To make your own type `!Unpin`, add a field of type `std::marker::PhantomPinned`; the auto trait then fails for the whole struct. The reverse direction is also possible: `impl Unpin for MyType {}` is a **safe** impl, because `Unpin` is a safe trait. That is fine for a type whose code never relies on pinning, such as a future combinator that keeps its inner future in a `Pin<Box<F>>`. It becomes unsound only in combination with `unsafe` projection code that assumes a field stays pinned, which is why writing such projections is left to unsafe code or a projection macro. A negative impl, `impl !Unpin for MyType {}`, is not available on stable Rust. ## Why futures care `Future::poll` takes `self: Pin<&mut Self>`. For an `Unpin` future, such as a hand-written state machine whose fields are all `Unpin` or a `Pin<Box<dyn Future>>`, `Pin::new(&mut fut)` is enough to poll it, and APIs like `futures::future::select`, `StreamExt::next` and `FutureExt::poll_unpin` accept it directly. For a `!Unpin` future, the caller must pin it first. The `Unpin` docs describe this as the trait's purpose: futures that do not care about pinning skip the restrictions, while those that need pinning can still be implemented soundly. - Passing a `!Unpin` future where `Unpin` is required gives the dedicated message "`...` cannot be unpinned". - Adding `F: Unpin` to a combinator's bounds is the simplest way to write it without projection, at the cost of making callers box async futures.
- Is it unsafe to write `impl Unpin for MyFuture {}` by hand?No, `Unpin` is a safe trait, and the impl is sound as long as no code relies on `MyFuture`'s fields staying pinned. It becomes a soundness bug only next to `unsafe` projection code that hands out `Pin<&mut Field>` for a `!Unpin` field, because safe code could then move that field.
- Does `T: Unpin` mean a value of type `T` can never be pinned?No. You can still create `Pin<&mut T>` or `Pin<Box<T>>`, for instance to call `Future::poll`. The pin simply imposes no restrictions: `Pin::new`, `get_mut` and `DerefMut` all work, so the value can be moved out again at will.
- Says Unpin means the value cannot be moved.
- Thinks Box<T> is Unpin only when T is Unpin.
- Believes implementing Unpin by hand requires an unsafe impl.
- Claims a type holding PhantomPinned still gets Unpin automatically.
- Says Unpin affects moves of values that are not behind a Pin.