Search code examples
rustactix-web

What does this # line of code mean in Rust?


Im learning rust and I came across this sample code:

use actix_web::{middleware, web, App, HttpRequest, HttpServer};

async fn index(req: HttpRequest) -> &'static str {
    println!("REQ: {req:?}");
    "Hello world!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "actix_web=info");
    env_logger::init();

    HttpServer::new(|| {
        App::new()
            // enable logger
            .wrap(middleware::Logger::default())
            .service(web::resource("/index.html").to(|| async { "Hello world!" }))
            .service(web::resource("/").to(index))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

As someone coming from Java, I dont know what this line of code means:

#[actix_web::main]

If I remove that and run the program, the error says 'main function cannot be async' , so it must be important.

Does anyone have link to documentation explaining what it is - the use of pound (#) sign?


Solution

  • This is an attribute. There are various kinds of attributes. In this case, this is an proc macro attribute, actix_web::main. It takes the item annotated with it (async fn main()) and transforms it into some other thing, usually some variation of the original code.

    For example, this attribute prepares the Actix runtime and allows you to have an async main (in reality, main() cannot be async, but this attribute transforms it into something like fn main() -> ... { actix_web::rt::System::new().block_on(async move { ... }) }).