Rust: Why are there no async traits?

pub trait MyTrait {
    async fn execute_async([...]) -> [...] // this is illegal
    fn execute_async2([...]) -> impl Future<[...]> // this is also illegal


Thanks to @alice for the answer: She said:

The main problem is because two functions [...] might return a different type. This means that if two people implement the same trait, they aren't going to be returning the same thing, and all implementations of a trait must return the same type

Alice suggests to, instead, return a Box and use an async block within the implementation.

1 Like

Until this is implemented better in the language, you may find #[async_trait] useful which lets trait methods be written using async syntax and turns them into Box + async block the way that you would otherwise do by hand.

use async_trait::async_trait

pub trait MyTrait {
    async fn execute_async(/* ... */) -> /* ... */

Nice crate you made! This is turning out to be a useful thread for others who may ask a similar question as I.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.