maybe_async_trait

Attribute Macro maybe_async_trait 

Source
#[maybe_async_trait]
Expand description

Conditionally add async keyword to functions.

Parses a trait or an impl block and conditionally adds the async keyword to methods that are annotated with #[maybe_async], depending on the async feature flag being enabled. Additionally, if applied to a trait definition or impl block, it will add #[async_trait::async_trait(?Send)] to the it.

For example, given the following trait definition:

#[maybe_async_trait]
trait ExampleTrait {
    #[maybe_async]
    fn hello_world(&self);

    fn get_hello(&self) -> String;
}

And the following implementation:

#[maybe_async_trait]
impl ExampleTrait for MyStruct {
    #[maybe_async]
    fn hello_world(&self) {
        // ...
    }

    fn get_hello(&self) -> String {
        // ...
    }
}

When the async feature is enabled, this will be transformed into:

#[async_trait::async_trait(?Send)]
trait ExampleTrait {
    async fn hello_world(&self);

    fn get_hello(&self) -> String;
}

#[async_trait::async_trait(?Send)]
impl ExampleTrait for MyStruct {
    async fn hello_world(&self) {
        // ...
    }

    fn get_hello(&self) -> String {
        // ...
    }
}

When the async feature is disabled, the code remains unchanged, and neither the async keyword nor the #[async_trait::async_trait(?Send)] attribute is applied.