Attribute Macro async_trait

Source
#[async_trait]
Expand description

The #[async_trait] macro is used to desugar async functions in traits to return impl Future + Send.

This macro is required mainly to get around the current limitation of async functions in traits, which would produce a lint warning for async_fn_in_trait if bare async functions are defined in a trait.

The default approach adopted by CGP is to always include a Send bound on the desugared Future, so that any async function that indirectly calls the method can still implement Send be be used with libraries such as tokio::spawn.

It is possible to remove default Send by deactivating the send feature in the cgp-async crate. However, the removal may be unreliable, as the feature flag could still be accidentally enabled by one of the dependencies.

Note that although the macro shares the same name as the async-trait crate, it is implemented very differently. The other crate with the same name returns a Pin<Box<dyn Future + Send>>, while this macro returns a impl Future + Send.

§Example

Given the following trait definition:

#[async_trait]
pub trait CanRun {
    async fn run(&self);
}

The macro would desugar it to the following:

pub trait CanRun {
    fn run(&self) -> impl Future<Output = ()> + Send;
}