In Rust, why do `futures::future::select(fut, tick)` and `(&mut fut).await` on an `async fn` future fail with E0277 "cannot be unpinned", and what fixes it?
answer
- the bound is on the callee
- async futures are not Unpin
- Pin<&mut F> is itself Unpin
- pin! locally, Box::pin to keep it
basics
~10 sfutures::future::select and impl Future for &mut F require F: Unpin, and rustc never makes an async future Unpin. Pin it first with std::pin::pin! (or Box::pin to keep it) and pass fut.as_mut().
solid answer
~50 sSome APIs poll a future through a plain `&mut F` or move it after polling: `futures::future::select` takes `A: Future + Unpin` and hands the losing future back, `StreamExt::next` needs `Self: Unpin`, and `(&mut fut).await` goes through `impl<F: Future + Unpin> Future for &mut F`. An `async fn` or `async` block future is `!Unpin`, so rustc reports E0277 "`{async fn body of ...}` cannot be unpinned". The fix is to pin the future once and pass a pinning pointer, which is `Unpin` even when its pointee is not: `let mut fut = pin!(parse_frame(buf));` then `select(tick, fut.as_mut())` or `(&mut fut).await`. Use `Box::pin` instead when the pinned future must outlive the scope, be returned or be stored. Pinning once outside a loop also keeps one future alive across iterations instead of boxing and restarting a new one each time.
code
plaintext · 13 lineserror[E0277]: `{async fn body of parse_frame()}` cannot be unpinned
--> src/bin/s1bad.rs:16:30
|
16 | match future::select(parse, tick).await {
| -------------- ^^^^^ within `impl futures::Future<Output = usize>`, the trait `Unpin` is not implemented for `{async fn body of parse_frame()}`
| |
| required by a bound introduced by this call
|
= note: consider using the `pin!` macro
consider using `Box::pin` if you need to access the pinned value outside of the current scope
note: required by a bound in `futures::future::select`
85 | A: Future + Unpin,
| ^^^^^ required by this bound in `select`go deeper
Recognise the 'cannot be unpinned' wording as an Unpin bound and know the two fixes rustc's note names: pin! for a local future, Box::pin for one you keep.
Explain where the bound comes from: select's A: Unpin, StreamExt::next's Self: Unpin, and the impl Future for &mut F. Show that Pin<&mut F> is Unpin and passes with as_mut().
Spot the loop that boxes a fresh future each iteration to dodge the error and loses its progress; pin once outside the loop, poll with as_mut(), and replace it with Pin::set.
Treat repeated pinning friction as an API signal: a combinator that demands Unpin pushes boxing onto every caller, while one taking Pin<&mut F> or pinning internally keeps call sites allocation-free.
## The error and where its bound comes from The message reads `error[E0277]: `{async fn body of parse_frame()}` cannot be unpinned`. E0277 is the general "trait bound not satisfied" error; the custom wording comes from the `Unpin` trait itself, which in `core::marker` carries a `#[diagnostic::on_unimplemented]` message "`{Self}` cannot be unpinned" and two notes: *consider using the `pin!` macro* and *consider using `Box::pin` if you need to access the pinned value outside of the current scope*. The bound is not on your future: it is on the API you handed the future to. Three common places put it there: - **`futures::future::select(a, b)`** declares `A: Future + Unpin, B: Future + Unpin`. It stores both futures, polls them through `poll_unpin`, and returns the unfinished one inside its `Either` output, which means moving a future that may already have been polled. That move is only sound when the type does not care about being moved. - **`StreamExt::next(&mut self)`** has `where Self: Unpin`, because it polls the stream through a plain `&mut` borrow. - **`(&mut fut).await`** uses std's `impl<F: ?Sized + Future + Unpin> Future for &mut F`, whose `poll` builds `Pin::new(&mut **self)`, and `Pin::new` exists only for `Unpin` targets. ## Why the async future is not `Unpin` `Unpin` is an auto trait, so most types get it for free. Futures made by `async fn` and `async` blocks do not: rustc marks them `!Unpin` even when, like `async { 1 }`, they hold no borrow at all, because their generated state can contain references into itself once polled. The material on self-referential futures explains that mechanism; for this error the point is only that the bound cannot be met by the bare future. ## The fix: pin once, pass a pinning pointer A **pinning pointer** such as `Pin<&mut F>` or `Pin<Box<F>>` is itself `Unpin`, even when `F` is not, and it implements `Future` whenever its target does. Moving the pointer moves nothing the future depends on. So the repair is: 1. Pin the future where you create it: `let mut parse = pin!(parse_frame(buf));`. `std::pin::pin!` moves the value into local storage of the current scope and gives back `Pin<&mut F>`. 2. Pass a reborrow each time it is polled: `select(tick, parse.as_mut())`. `Pin::as_mut` produces a fresh `Pin<&mut F>` without giving up your binding. 3. Await it later with `parse.await` or `(&mut parse).await`; the future keeps the progress it already made. When the pinned future must leave the scope, be returned, or be stored in a struct or a `Vec`, use `Box::pin(fut)` (or `FutureExt::boxed`, which also requires `Send` and yields `Pin<Box<dyn Future<Output = T> + Send>>`). It costs one heap allocation. | Situation | Pin with | Pass | |---|---|---| | Future used only inside this function or async block | `pin!(fut)` | `fut.as_mut()` or `&mut fut` | | Future returned, stored, or kept in a collection | `Box::pin(fut)` | `fut.as_mut()` or the box itself | | Replacing the pinned future with a new one | either | `fut.set(new_future)` | ## The loop bug the error often hides A common reaction to the error is to write `select(Box::pin(read_frame()), tick())` inside the loop body. That compiles, because `Pin<Box<F>>` is `Unpin`, but it allocates a new future on every iteration and, whenever `tick` wins, drops the unfinished one: a half-read frame or a pending request is thrown away and begun again next time round. Pinning the future once **outside** the loop and passing `as_mut()` keeps one future alive across iterations, and `Pin::set` replaces it in place when it finishes and you want the next one. ## What does not fix it - Writing `impl Unpin` for the future is impossible: the type of an `async fn` future is anonymous and you cannot name it in an impl. - Wrapping it in `Box::new` without pinning gives `Box<F>`, whose `Future` impl again requires `F: Unpin`. - Calling `Pin::new(&mut fut)` fails with the same E0277, because `Pin::new` exists only for `Unpin` targets; the everyday safe constructors for a `!Unpin` value are `pin!` and `Box::pin`. - Calling `get_mut()` on an already pinned async future to obtain `&mut F` fails the same way: `Pin::get_mut` also requires an `Unpin` target, which is exactly the property the future lacks. Once you read the message as "this API wants something it may move", the fix has one shape: give it a pointer to a pinned future instead of the future itself.
- Why does `futures::future::select` need `Unpin` at all, when `.await` on the bare future works?`.await` pins the future it awaits inside the enclosing future's state, so a `!Unpin` future is fine. `select` instead takes its futures by value, polls them, and hands the unfinished one back in its `Either` output, which moves it after polling. Requiring `Unpin` makes that move sound; a `Pin<&mut F>` satisfies it because moving the pointer leaves `F` in place.
- When should you choose `Box::pin` over `pin!` to fix this error?When the pinned future must outlive the current scope: returned from a function, stored in a struct field or a `Vec`, or handed to code that keeps it. `pin!` borrows a local of the current scope, so its `Pin<&mut F>` cannot escape. `Box::pin` costs one heap allocation but gives an owned `Pin<Box<F>>` that can go anywhere.
- Says the future itself must be changed to implement Unpin by hand.
- Boxes a fresh future inside the loop, restarting the work every iteration.
- Thinks Box::new(fut) is enough, without pinning the box.
- Believes Pin::new(&mut fut) works for an async fn future.
- Claims pinning copies the future or makes it slower to poll.