Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does #[macro_use] before an extern crate statement mean?

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;
like image 928
sdgfsdh Avatar asked Mar 01 '19 23:03

sdgfsdh


3 Answers

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.

like image 148
Shepmaster Avatar answered Oct 21 '22 23:10

Shepmaster


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].

like image 29
at54321 Avatar answered Oct 21 '22 21:10

at54321


// all the rockets macros import globally. 
//you can use rocket macros anywhere in your application
#[macro_use] extern crate rocket;
like image 23
Yilmaz Avatar answered Oct 21 '22 23:10

Yilmaz