In Rust, I sometimes see #[macro_use]
before an extern crate
statement:
#[macro_use]
extern crate gotham_derive;
What does this do compared to not having #[macro_use]
?
extern crate gotham_derive;
It means to import ("use") the macros from the crate.
As of Rust 1.30, this syntax is no longer generally needed and you can use the standard use
keyword instead.
Review the macros chapter from the first edition of The Rust Programming Language for more detail.
As Shepmaster already explained, in newer Rust versions (edition 2018+) this syntax is no longer needed. However, there are still cases when it might come in handy, like global macro imports. Here is an excerpt from Rocket's documentation, which explains why they prefer having #[macro_use] extern crate rocket;
in their code:
Throughout this guide and the majority of Rocket's documentation, we import rocket explicitly with
#[macro_use]
even though the Rust 2018 edition makes explicitly importing crates optional. However, explicitly importing with#[macro_use]
imports macros globally, allowing you to use Rocket's macros anywhere in your application without importing them explicitly.You may instead prefer to import macros explicitly or refer to them with absolute paths:
use rocket::get;
or#[rocket::get]
.
// all the rockets macros import globally.
//you can use rocket macros anywhere in your application
#[macro_use] extern crate rocket;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With