Skip to content

unused_async emitted when trait bounds where function is used require it to be async #9359

Closed
@aonkeeper4

Description

@aonkeeper4

Summary

When using actix-web, Clippy warned me that the async on one of my handler functions was unused as there was no await. It turned out that the trait bounds on the .to() method of actix-web::route::Route required that the handler function implemented Handler<Args> which requires an async function.

Lint Name

unused_async

Reproducer

I tried this code:

use actix_web::{web, App, HttpServer};
use std::sync::Mutex;

struct AppStateWithCounter {
    counter: Mutex<i32>, // <- Mutex is necessary to mutate safely across threads
}

async fn index(data: web::Data<AppStateWithCounter>) -> String {
    if let Ok(mut counter) = data.counter.lock() { // <- get counter's MutexGuard
        *counter += 1; // <- access counter inside MutexGuard
        format!("Request number: {counter}") // <- response with count
    } else {
        "Unable to access counter".to_string()
    }
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // Note: web::Data created _outside_ HttpServer::new closure
    let counter = web::Data::new(AppStateWithCounter { 
        counter: Mutex::new(0),
    });

    HttpServer::new(move || {
        // move counter into the closure
        App::new()
            .app_data(counter.clone()) // <- register the created data
            .route("/", web::get().to(index))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

I saw this happen:

warning: unused `async` for function with no await statements
  --> src\main.rs:8:1
   |
8  | / async fn index(data: web::Data<AppStateWithCounter>) -> String {
9  | |     if let Ok(mut counter) = data.counter.lock() { // <- get counter's MutexGuard
10 | |         *counter += 1; // <- access counter inside MutexGuard
11 | |         format!("Request number: {counter}") // <- response with count
...  |
14 | |     }
15 | | }
   | |_^
   |
   = note: `-W clippy::unused-async` implied by `-W clippy::pedantic`
   = help: consider removing the `async` from this function
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#unused_async

Version

rustc 1.63.0 (4b91a6ea7 2022-08-08)
binary: rustc
commit-hash: 4b91a6ea7258a947e59c6522cd5898e7c0a6a88f
commit-date: 2022-08-08
host: x86_64-pc-windows-gnu
release: 1.63.0
LLVM version: 14.0.5

Additional Labels

@rustbot label + I-suggestion-causes-error

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: Clippy is not doing the correct thingI-false-positiveIssue: The lint was triggered on code it shouldn't haveI-suggestion-causes-errorIssue: The suggestions provided by this Lint cause an ICE/error when applied

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions