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

sdg*_*sdh 17 rust

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

#[macro_use]
extern crate gotham_derive;
Run Code Online (Sandbox Code Playgroud)

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

extern crate gotham_derive;
Run Code Online (Sandbox Code Playgroud)

at5*_*321 16

正如 Shepmaster 已经解释的那样,在较新的 Rust 版本(2018+ 版)中不再需要此语法。然而,在某些情况下它仍然可能派上用场,例如全局宏导入以下是Rocket 文档的摘录,解释了为什么他们更喜欢#[macro_use] extern crate rocket;在代码中包含:

在本指南和 Rocket 的大部分文档中,我们显式导入 Rocket,#[macro_use]尽管 Rust 2018 版本使显式导入 crates 成为可选。但是,通过#[macro_use]全局导入宏显式导入,允许您在应用程序中的任何位置使用 Rocket 的宏,而无需显式导入它们。

您可能更喜欢显式导入宏或使用绝对路径引用它们:use rocket::get;#[rocket::get]


She*_*ter 12

这意味着从板条箱中导入(“使用”)宏。

Rust 1.30 开始,通常不再需要这种语法,您可以使用标准use关键字代替。

查看Rust 编程语言第一版中宏章节以获取更多详细信息。

  • @HasanAYousef `use serde_derive;` 是一个无操作,就像任何其中没有 `::` 的 `use` 语句一样。您可能想要 `use serde_derive::{Deserialize, Serialize};` 或类似的。 (4认同)
  • 我尝试使用 1use serde_derive;` 而不是 `#[macro_use] extern crate serde_derive;` 但失败了! (3认同)