【问题标题】:What does #[macro_use] before an extern crate statement mean?extern crate 语句之前的#[macro_use] 是什么意思?
【发布时间】:2019-03-01 23:13:51
【问题描述】:

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

#[macro_use]
extern crate gotham_derive;

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

extern crate gotham_derive;

【问题讨论】:

  • 我对 Rust 的宏不是很熟悉,但 it appears 在 Rust 2015 中需要 #[macro_use] 来通知编译器您正在使用 crate 中定义的宏。

标签: rust rust-macros


【解决方案1】:

表示从 crate 中导入(“使用”)宏。

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

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

【讨论】:

  • 我尝试使用 1use serde_derive;` 而不是 #[macro_use] extern crate serde_derive; 但失败了!
  • @HasanAYousef use serde_derive; 是一个空操作,就像任何没有 ::use 语句一样。你可能想要use serde_derive::{Deserialize, Serialize}; 或类似的。
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:
    // all the rockets macros import globally. 
    //you can use rocket macros anywhere in your application
    #[macro_use] extern crate rocket;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 2021-06-27
      • 2011-11-18
      • 2012-05-07
      • 2011-08-15
      • 2023-03-12
      • 2013-05-12
      相关资源
      最近更新 更多