【问题标题】:"cannot find macro" error in the macro's own doc test宏自己的文档测试中的“找不到宏”错误
【发布时间】:2015-07-27 02:41:19
【问题描述】:

我正在尝试将文档测试添加到我正在导出的 Rust 宏中。像这样的:

/// Usage:
///
/// ```
/// let x = addone!(100);
/// ```
#[macro_export]
macro_rules! addone {
    ($x:expr) => ($x + 1)
}

如果我对此运行cargo test,我会得到

failures:

---- src/lib.rs - addone (line 3) stdout ----
    error: cannot find macro `addone!` in this scope
 --> src/lib.rs:2:9
  |
2 | let x = addone!(100);
  |         ^^^^^^

我想不出在 doc 测试中添加 macro_use 的合法方式,所以没有运气。

macros in Rust's standard library 遵循与上面代码相​​同的格式,所以我期待它能够工作。

【问题讨论】:

    标签: rust


    【解决方案1】:

    如果文档测试在代码中找不到这些元素,则会自动将代码块包装在 extern crate foo; fn main() { … } 中,但要获得导出的宏,您需要 extern crate foo; 上的 #[macro_use] 属性。

    因此,你应该这样写:

    /// Usage:
    ///
    /// ```
    /// # #[macro_use] extern crate foo; fn main() {
    /// let x = addone!(100);
    /// # }
    /// ```
    #[macro_export]
    macro_rules! addone {
        ($x:expr) => ($x + 1)
    }
    

    (以 为前缀的行在输出中隐藏,但在为 doc 测试编译的代码中包含 sans 标记。)

    The Rust Programming Language, first edition 对此进行了介绍。

    至于std,在所有缺少#![no_std] crate 属性的 crate 中都有一个隐含的#[macro_use] extern crate std;,因此它的宏立即起作用。

    【讨论】:

    • 完美运行。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    相关资源
    最近更新 更多