14 May 2022

Rust's future combinators

The Rust Future module defines many ways to chain and convert futures. This post summarises a few common ones as a reference table.

Liberties taken:

  • the result types below are given as Future<T> but this is not accurate. For example, ready returns a Ready<T>, lazy returns a Lazy<T> and so on. But these can be used as if they were Future<Output=T>. For my purposes this shorthand works, as I want to think of them as futures I can await on or combine with other futures.
  • I’ve used Vec in the table below for arguments, where the more general iterator is acceptable. I’ve done this to keep the table short.

There is a playground with a few of these functions as an example.

Basic combinators

With use futures::future to bring these functions into scope.

FunctionArgumentsResult type
lazyFnOnce -> TFuture<T>
joinFuture<A>, Future<B>Future<(A,B)>
select (“race”)(Future<T>, Future<T>)Future<Result<(T, Future<T>)>>

See the Future module for the complete list.

Combinators available via FutureExt

These require a use futures::future::FutureExt; statement, and are functions on a Future<T>.

FunctionArgumentsResult type
mapFnOnce(T) -> RFuture<R>
then (“flatmap”)FnOnce(T) -> Future<R>Future<R>

There are many more in the FutureExt module.

Combinators to simplify working with futures that carry Result<T, E>

Some of these functions need a use futures::future::TryFutureExt; statement to bring them into scope.

FunctionArgumentsResult type
map_okFnOnce(T) -> TFuture<Result<T,E>>
map_errFnOnce(E) -> EFuture<Result<T,E>>
and_thenFnOnce(T) -> Future<Result<T,E>>Future<Result<T,E>>

See the TryFutureExt module for more.