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 aReady<T>
,lazy
returns aLazy<T>
and so on. But these can be used as if they wereFuture<Output=T>
. For my purposes this shorthand works, as I want to think of them as futures I canawait
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.
Function | Arguments | Result type |
---|---|---|
ready | T | Future<T> |
lazy | FnOnce -> T | Future<T> |
join | Future<A>, Future<B> | Future<(A,B)> |
join_all | Vec<Future<A>> | Future<Vec<A>> |
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>
.
Function | Arguments | Result type |
---|---|---|
map | FnOnce(T) -> R | Future<R> |
then (“flatmap”) | FnOnce(T) -> Future<R> | Future<R> |
inspect | FnOnce(T) | Future<T> |
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.
Function | Arguments | Result type |
---|---|---|
ok::<T,E> | T | Future<Result<T,E>> |
err::<T,E> | E | Future<Result<T,E>> |
map_ok | FnOnce(T) -> T | Future<Result<T,E>> |
map_err | FnOnce(E) -> E | Future<Result<T,E>> |
and_then | FnOnce(T) -> Future<Result<T,E>> | Future<Result<T,E>> |
select_ok | Vec<Future<Result<T,E>>> | Future<Result<(T,Vec<Future<T>>)>> |
See the TryFutureExt module for more.