In a hand-written Rust future combinator `CountPolls<F>` wrapping an inner future, why does `self.inner.poll(cx)` fail, and how does pin projection fix it?
answer
- poll needs Pin<&mut F>
- Pin<&mut Self> gives no &mut field
- structural vs not structural
- #[pin] in pin_project!
basics
~20 spoll needs Pin<&mut F>, but Pin<&mut Self> yields neither that nor &mut self.inner when F may be !Unpin (E0599). Project the pin: pin_project! with #[pin] inner gives Pin<&mut F> for it and &mut for the rest.
solid answer
~40 sInside `fn poll(self: Pin<&mut Self>, cx)`, `self.inner` is reached through `Deref`, so it is a plain place of type `F`, and `Future::poll` is only callable on `Pin<&mut F>`; rustc reports E0599 "no method named `poll` found for type parameter `F`". Even `self.polls += 1` fails with E0594, because `Pin<&mut CountPolls<F>>` has no `DerefMut` unless `F: Unpin`. The fix is **pin projection**: turning `Pin<&mut Self>` into `Pin<&mut F>` for the inner future (a **structurally pinned** field) and `&mut u32` for the counter (not structural). `pin_project_lite::pin_project!` generates that `project()` method safely when you mark `#[pin] inner`. The simpler alternatives are bounding `F: Unpin` and calling `Pin::new(&mut self.inner).poll(cx)`, which pushes `Box::pin` onto callers, or storing `Pin<Box<F>>`, which allocates. Following rustc's hint to `pin!` the field inside `poll` does not work.
code
plaintext · 10 lineserror[E0599]: no method named `poll` found for type parameter `F` in the current scope
--> src/bin/s4bad.rs:14:26
|
10 | impl<F: Future> Future for CountPolls<F> {
| - method `poll` not found for this type parameter
...
14 | match self.inner.poll(cx) {
| ^^^^ method not found in `F`
|
help: consider pinning the expression with `std::pin::pin!()` and assigning that to a new bindinggo deeper
Know that a wrapper future must poll its inner future through Pin<&mut F>, and that a library macro usually provides that.
Read both errors: E0599 because poll needs Pin<&mut F>, E0594 because Pin<&mut Self> has no DerefMut for a possibly !Unpin struct.
Choose per field between structural and non-structural pinning, use pin_project! with #[pin] and PinnedDrop, and know when an F: Unpin bound or Pin<Box<F>> is the simpler trade.
Set the library's combinator convention: projection macros keep callers allocation-free, Unpin bounds simplify the code but tax every async caller, and hand-written unsafe projection needs review.
## The combinator and the two errors A combinator is a future that wraps another future and adds behaviour, here counting how many times the inner one was polled: ```rust struct CountPolls<F> { inner: F, polls: u32 } impl<F: Future> Future for CountPolls<F> { type Output = (F::Output, u32); fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.polls += 1; // E0594 on its own match self.inner.poll(cx) { /* E0599 */ } } } ``` rustc 1.99.1 rejects `self.inner.poll(cx)` with E0599, "no method named `poll` found for type parameter `F` in the current scope". `Future::poll` takes `self: Pin<&mut Self>`, and `self.inner` reached through a `Pin<&mut CountPolls<F>>` is just a place of type `F`. Remove that line and `self.polls += 1` fails too, with E0594 "cannot assign to data in dereference of `Pin<&mut CountPolls<F>>`": `Pin` implements `DerefMut` only when the pointee is `Unpin`, and `CountPolls<F>` is `Unpin` only when `F` is. The compiler adds a hint, "consider pinning the expression with `std::pin::pin!()`". Inside `poll` that is the wrong repair: `let inner = pin!(self.inner);` fails with E0507, "cannot move out of dereference of `Pin<&mut CountPolls<F>>`", and even a future pinned afresh in every call would not be the same future between polls. ## Projection: what each field should become **Pin projection** means turning `Pin<&mut Struct>` into references to its fields. For each field the author decides: - **Structurally pinned**: the field is pinned whenever the struct is, so the projection yields `Pin<&mut Field>`. A wrapped future must be structural, because polling needs a pinned reference to it. - **Not structural**: the field is never considered pinned, so the projection yields `&mut Field`. A counter, a timestamp or a config value belongs here. Writing projections by hand needs `unsafe` (`Pin::map_unchecked_mut` or `get_unchecked_mut`), and the `pin` module lists the obligations a structural field brings: 1. The struct may be `Unpin` only if all structurally pinned fields are; the default auto-trait rule already gives that. 2. The `Drop` impl must treat `self` as if it were `Pin<&mut Self>`, and so the struct must not be `#[repr(packed)]`. 3. Once pinned, the struct's storage must not be reused without running the structural fields' destructors. 4. No other method may move data out of a structural field while the struct is pinned, such as an `Option::take`-like accessor. ## Doing it safely with `pin-project-lite` `pin_project_lite::pin_project!` (a declarative macro, so it pulls in no proc-macro dependencies) writes the projection and enforces those rules: ```rust pin_project! { struct CountPolls<F> { #[pin] inner: F, // Pin<&mut F> after project() polls: u32, // &mut u32 after project() } } // in poll: let this = self.project(); *this.polls += 1; this.inner.poll(cx) ``` What the macro guarantees: - It generates `project()` (and `project_ref()`), returning `Pin<&mut F>` for `#[pin]` fields and `&mut T` for the rest. - It implements `Unpin` for the struct only when every `#[pin]` field is `Unpin`. - It refuses a plain `impl Drop` for the type; you write an `impl PinnedDrop` block inside the macro instead. - It refuses `#[repr(packed)]` structs. Its limits: no tuple structs or tuple variants, enums need a named projection type (`#[project = EnumProj]`), and error messages are poor. A `PhantomPinned` field makes the struct `!Unpin` only if it carries `#[pin]`; `#[project(!Unpin)]` is the shorthand for the same effect. The `pin-project` crate is the proc-macro version with more features. ## Reading the generated projection It helps to know what the macro produces, because the same shape appears in hand-written code and in other crates: - A hidden **projection struct** with the same field names, holding `Pin<&'a mut F>` for each `#[pin]` field and `&'a mut T` for the others. `project()` consumes `self: Pin<&mut Self>` and returns it, so call `self.project()` once at the top of `poll` and use `this.inner` and `this.polls` from then on. - Because `project()` consumes the pinned reference, calling it twice needs `self.as_mut().project()` for the first call, the same reborrow pattern as `Pin::as_mut` elsewhere. - For a combinator that must poll the inner future again in a loop, keep the projected `Pin<&mut F>` and call `as_mut()` on it before each `poll`. Enums work the same way with a named projection type, which is how state-machine combinators such as "first run future A, then future B" are usually written. ## The alternatives without projection | Approach | `poll` body | Cost | |---|---|---| | Bound `F: Future + Unpin` | `Pin::new(&mut self.inner).poll(cx)` and `self.polls += 1` | callers must `Box::pin` any async future they pass | | Store `inner: Pin<Box<F>>` | `self.inner.as_mut().poll(cx)` | one heap allocation per combinator | | `pin_project!` with `#[pin] inner` | `let this = self.project();` | none at run time | | Hand-written `unsafe` projection | `map_unchecked_mut` | you own every obligation listed above | Library code that wraps arbitrary futures usually projects, because a combinator that demands `Unpin` makes every `async fn` caller allocate.
- When is it fine to make a combinator field not structurally pinned?When nothing needs it pinned: counters, timestamps, configuration, or a field that is itself a `Pin<Box<F>>`. Such a field can be reached as `&mut T` from `Pin<&mut Self>`, and the struct may even implement `Unpin` regardless of that field's type. What you must not do is later write unsafe code that assumes it is pinned.
- Why does pin-project-lite stop you from writing `impl Drop` for a projected struct?`Drop::drop` takes `&mut self`, which would let you move a structurally pinned field out after it was pinned. The macro rejects a direct `Drop` impl and offers `impl PinnedDrop` inside the macro, whose method receives `Pin<&mut Self>`, so cleanup goes through the same projection rules.
- Follows the compiler hint and calls pin!(self.inner) inside poll.
- Uses get_unchecked_mut to reach the field without stating why it is sound.
- Assumes pin_project! accepts tuple structs, as the pin-project crate does.
- Thinks a PhantomPinned field without #[pin] makes a pin_project! struct !Unpin.
- Adds impl Drop to a pin_project! struct and expects it to compile.