How do I apply #[must_use] to an async function?

Viewed 229

#[must_use] seems to have no effect on async functions. This code generates no warnings:

#[must_use]
async fn launch_missiles() -> u32 {
    42
}

#[tokio::main]
async fn main() {
    launch_missiles().await;
}

(Playground)

Is this expected behavior, or is it a language design flaw / compiler bug?

If it's expected, what are my alternatives? It works fine if the return type is #[must_use] so I've started creating a MustUse<_> wrapper type. It seems like overkill, though. Am I missing a simpler workaround?

1 Answers

I think the best you can currently do (without manually implementing what async is doing) is to return a #[must_use] wrapper type:

#[must_use]
struct MustUse<T : ?Sized>(T);

#[must_use]
async fn launch_missiles() -> MustUse<u32> {
    MustUse(42)
}

#[tokio::main]
async fn main() {
    launch_missiles().await;
}

Playground

Related