Issue
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!"
}
#[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]
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 { ... }) }
).
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.