[SOLVED] What does this # line of code mean in Rust?


This Content is from Stack Overflow. Question asked by Joona Ritva

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!"

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

    HttpServer::new(|| {
            // enable logger
            .service(web::resource("/index.html").to(|| async { "Hello world!" }))
    .bind(("", 8080))?

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


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


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 { ... }) }).

This Question was asked in StackOverflow by Joona Ritva and Answered by Chayim Friedman It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?