extern crate 语句之前的#[macro_use] 是什么意思?

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

在 Rust 中,我有时会在 extern crate 语句之前看到 #[macro_use]

#[macro_use]
extern crate gotham_derive;

与没有 #[macro_use] 相比,这有什么作用?

extern crate gotham_derive;

意思是从 crate 导入("use")宏。

Rust 1.30 开始,通常不再需要此语法,您可以改用标准 use 关键字。

查看 macros chapter from the first edition of The Rust Programming Language 了解更多详情。

正如 Shepmaster 已经解释的那样,在较新的 Rust 版本(2018+ 版)中不再需要这种语法。但是,在某些情况下它可能会派上用场,例如 global macro imports。这是 Rocket's documentation 的摘录,它解释了为什么他们更喜欢在代码中使用 #[macro_use] extern crate rocket;

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;