skip to content

In Rust, what does the IntoFuture trait change about .await, and why would a request builder implement it instead of Future?

level: middleimportance: nice to knowfreq 30%

answer

  1. the first step of .await
  2. blanket impl for every Future
  3. configure, then await
  4. a nameable associated type

basics

~20 s

Since Rust 1.64, .await first calls IntoFuture::into_future on its operand; every Future gets that for free. A builder implements IntoFuture so callers can chain settings and write .await directly, with the request future built only at that point.

solid answer

~40 s

`.await` does not require its operand to be a `Future`; it requires `IntoFuture`, and the first thing it does is call `into_future`. Stable since Rust 1.64, the trait has `type Output`, `type IntoFuture: Future<Output = Self::Output>` and `fn into_future(self)`, and a blanket impl makes every `Future` return itself. That lets an **async builder** stay a plain, configurable struct: `Upload::new(7).retries(3).await` sets fields by value and only becomes a future when awaited. Implementing `Future` on the builder instead would mix configuration with poll-time state. Generic code can accept `F: IntoFuture` to take both. One constraint: the associated type must be nameable on stable, so builders return a `std::future::Ready`, a hand-written future, or `Pin<Box<dyn Future + Send>>`.

code

rust · 26 lines
rust
use std::future::{IntoFuture, Ready, ready};

struct Upload { sensor: u32, retries: u8 }

impl Upload {
    fn new(sensor: u32) -> Self { Upload { sensor, retries: 0 } }
    fn retries(mut self, n: u8) -> Self { self.retries = n; self }
}

impl IntoFuture for Upload {
    type Output = String;
    type IntoFuture = Ready<String>;
    fn into_future(self) -> Self::IntoFuture {
        ready(format!("sensor {} sent, {} retries allowed", self.sensor, self.retries))
    }
}

async fn run() -> String {
    Upload::new(7).retries(3).await // .await calls into_future() first
}

fn main() {
    let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
    let mut fut = std::pin::pin!(run());
    println!("{:?}", std::future::Future::poll(fut.as_mut(), &mut cx));
}

go deeper

for a junior

Know that .await can be applied to things other than futures if they implement IntoFuture, and that ordinary futures implement it automatically.

for a middle

Explain that .await calls into_future first, describe the blanket impl, and show the builder pattern consuming self on .await.

for a senior

Discuss naming the associated type on stable: Ready, a hand-written future, or a boxed dyn Future, and the allocation that boxing costs.

for a principal

Weigh awaitable builders against an explicit send method for a public client library: ergonomics, discoverability, and boxing cost per call.

## What `.await` really accepts The Reference describes the operand of `.await` as an expression whose type implements **`std::future::IntoFuture`**, not `Future`. The very first step of `.await` is `IntoFuture::into_future(operand)`; only the future that call returns is pinned and polled. The trait was stabilised in **Rust 1.64**, and the 2024 edition added both `Future` and `IntoFuture` to the prelude. ```rust pub trait IntoFuture { type Output; type IntoFuture: Future<Output = Self::Output>; fn into_future(self) -> Self::IntoFuture; } ``` - **`Output`** is what the `.await` expression evaluates to. - **`IntoFuture`** (the associated type) is the concrete future that will be polled. - **`into_future(self)`** takes the value by ownership and produces that future. core also provides a **blanket impl**: every `F: Future` implements `IntoFuture` with `type IntoFuture = F`, and `into_future` returns `self`. That is why ordinary `.await` on an `async fn` call behaves exactly as before 1.64, and why `IntoFuture` and `Future` cannot both be implemented by hand for the same type: the blanket impl already covers any `Future`, and rustc 1.99 reports the overlap as E0119. ## The async builder pattern A sensor gateway's upload call has options: the sensor id, retries, a timeout. Without `IntoFuture`, the API needs a terminal method: `Upload::new(7).retries(3).send().await`. With it, the builder itself can be awaited: 1. `Upload::new(7)` returns a plain struct holding the settings. 2. `.retries(3)` takes `self` by value and returns the modified struct. 3. `.await` calls `into_future`, which consumes the finished configuration and builds the future that performs the upload. The `IntoFuture` docs name this as where implementing the trait is most useful: "async builder" types whose values are modified several times before being awaited. Making the builder implement `Future` directly is possible but muddier: the struct would need poll-time state (connections, buffers) mixed with configuration fields, and calling a setter after the first poll would make no sense. ## What rustc says when neither trait is implemented Awaiting a type that is neither a future nor `IntoFuture` fails with **E0277**. In rustc 1.99 the message reads "`Upload` is not a future", with the note "Upload must be a future or must implement `IntoFuture` to be awaited". That note comes from a `#[diagnostic::on_unimplemented]` attribute on the trait. ## Choosing the associated type The associated type must be named, and that is the practical difficulty: | Choice for `type IntoFuture` | When it fits | |---|---| | `std::future::Ready<T>` | the result is computable at once; useful in tests and examples | | a hand-written future struct | the hot path, where boxing per request matters | | `Pin<Box<dyn Future<Output = T> + Send>>` | the body is an `async move` block, which has an unnameable type | | `impl Future<Output = T>` | not on stable: rustc 1.99 rejects it with E0658, "`impl Trait` in associated types is unstable" | Most real builders box: `fn into_future(self) -> Self::IntoFuture { Box::pin(async move { /* send */ }) }`. The cost is one allocation per await. ## Accepting either in generic code A function can take `F: IntoFuture` instead of `F: Future`, and then both futures and builders work without an explicit `into_future()` call at the call site, as the std docs show with a generic `fut_to_string`. Inside, `fut.await` performs the conversion. ## Points that trip people up - `into_future` is just a method: calling it by hand yields a future, which, like any future, does nothing until polled. - Because `into_future` takes `self`, the builder is consumed by `.await`; to reuse a configuration, clone the builder first. - Before 1.64 the same API needed a terminal method; code written for older compilers often still has one. - `IntoFuture` changes only how `.await` obtains its future. The polling protocol, `Poll::Ready` and `Poll::Pending`, is unchanged. - A boxed future must be **pinned**: `Box<dyn Future<Output = T> + Send>` does not implement `Future`, because `Box<F>` is a future only when `F: Unpin`, and rustc 1.99 rejects that associated type with E0277. Use `Box::pin`, not `Box::new`. ## When not to bother An awaitable builder is an API nicety, not a capability. If an operation has no options, a plain `async fn` is simpler and needs no associated type at all. If the builder is also used synchronously, for example to produce a request description for logging, an explicit terminal method such as `send()` keeps the moment the work starts visible at the call site. `IntoFuture` earns its keep on client libraries whose calls take several optional settings and are almost always awaited straight away.

  • Can a type implement both Future and IntoFuture by hand?
    No. core's blanket impl already implements IntoFuture for every Future, so a second, hand-written impl would overlap and rustc rejects it with E0119, conflicting implementations of trait `IntoFuture`. A type picks one: Future for a value that is itself pollable, IntoFuture for a value that only becomes a future when awaited.
  • Why do most real builders set type IntoFuture to a boxed future?
    into_future usually wants to return an async move block, whose type has no name, and impl Trait in associated types is unstable in Rust 1.99. Pin<Box<dyn Future<Output = T> + Send>> is a nameable type that holds the block, at the cost of one heap allocation.

  • .await only works on types that implement Future.
  • IntoFuture runs the request when the builder is created.
  • You can implement Future and IntoFuture by hand for the same type.
  • type IntoFuture = impl Future works on stable Rust.
  • IntoFuture changes how the resulting future is polled.

Assumes Rust 1.99 on edition 2024; IntoFuture and .await calling into_future are stable since 1.64, and the 2024 edition put IntoFuture in the prelude.