How can I define an async method in a trait?

On stable Rust, async fn cannot be used in traits. There is ongoing work that will make this possible in the future, but the easiest solution currently is to use the async-trait crate:

#[async_trait]
trait Readable {
    async fn readable(&self) -> io::Result<()>;
}

#[async_trait]
impl Readable for Reader {
    async fn readable(&self) -> io::Result<()> {
        do_stuff().await
    }
}

To avoid having Send bound placed on the async trait methods, you can invoke the async trait macro as #[async_trait(?Send)] on both the trait and the impl blocks.

#![feature(async_fn_in_trait)]

On nightly, it is now possible to write async trait methods using the async_fn_in_trait feature:

#![feature(async_fn_in_trait)]

trait Readable {
    async fn readable(&self) -> io::Result<()>;
}


impl Readable for Reader {
    async fn readable(&self) -> io::Result<()> {
        do_stuff().await
    }
}

However, the current implementation is limited, and does not allow specifying Send or Sync bounds on the returned future. See the announcement post for details.

Associated Types

Another way of doing it is with an associated type:

trait Readable {
    type Output: Future<Output = io::Result<()>>;

    fn readable(&self) -> Self::Output;
}

When implementing this trait, you can use any type that implements Future, such as Ready from the standard library:

use std::future;

impl Readable for Reader {
    type Output = future::Ready<io::Result<()>>;
    
    fn readable(&self) -> Self::Output {
        future::ready(Ok(()))
    }
}

async functions return an opaque impl Future, so if you need to call one inside your function, you can’t have a concrete Output type. Instead, you can return an dynamically typed Future:

impl Readable for Reader {
    // or use the handy type alias from the futures crate:
    // futures::BoxFuture<'static, io::Result<()>>
    type Output = Pin<Box<dyn Future<Output = io::Result<()>>>>;
    
    fn readable(&self) -> Self::Output {
        Box::pin(async {
            do_stuff().await
        })
    }
}

Note that using these trait methods will result in a heap allocation and dynamic dispatch per function-call, just like with the async-trait crate. This is not a significant cost for the vast majority of applications, but is something to be considered.

Capturing References

One issue that may come up is the fact that the associated type Output does not have a lifetime, and therefore cannot capture any references:

struct Reader(String);

impl Readable for Reader {
    type Output = Pin<Box<dyn Future<Output = io::Result<()>>>>;
    
    fn readable(&self) -> Self::Output {
        Box::pin(async move {
            println!("{}", self.0);
            Ok(())
        })
    }
}
error: lifetime may not live long enough
  --> src/lib.rs:17:9
   |
16 |       fn readable(&self) -> Self::Output {
   |                   - let's call the lifetime of this reference `'1`
17 | /         Box::pin(async move {
18 | |             println!("{}", self.0);
19 | |             Ok(())
20 | |         })
   | |__________^ returning this value requires that `'1` must outlive `'static`

Associated types on stable Rust cannot have lifetimes, so you would have to restrict the output to a boxed future that captures from self to make this possible:

trait Readable {
    // note the anonymous lifetime ('_) that refers to &self
    fn readable(&self) -> Pin<Box<dyn Future<Output = io::Result<()>> + '_>>;
}

impl Readable for Reader {
    fn readable(&self) -> Pin<Box<dyn Future<Output = io::Result<()>> + '_>> {
        Box::pin(async move {
            println!("{}", self.0);
            Ok(())
        })
    }
}

This is actually exactly what the async-trait crate does under the hood.

Unstable Features

If you are on nightly, the story is better. You can enable the type_alias_impl_trait feature and use regular async/await syntax without boxing:

#![feature(type_alias_impl_trait)]

trait Readable {
    type Output: Future<Output = io::Result<()>>;

    fn readable(&self) -> Self::Output;
}


impl Readable for Reader {
    type Output = impl Future<Output = io::Result<()>>;
    
    fn readable(&self) -> Self::Output {
        async { ... }
    }
}

The borrowing issue still applies with the above code. However, with the recently stabilized generic associated type feature, you make Output generic over a lifetime and capture self:

trait Readable {
    type Output<'a>: Future<Output = io::Result<()>>;

    fn readable(&self) -> Self::Output<'_>;
}

And the previous example compiles, with zero boxing!

struct Reader(String);

impl Readable for Reader {
    type Output<'a> = impl Future<Output = io::Result<()>> + 'a;
    
    fn readable(&self) -> Self::Output<'_> {
        Box::pin(async move {
            println!("{}", self.0); // we can capture self!
            Ok(())
        })
    }
}

Leave a Comment