“找不到宏"宏自己的文档测试中的错误 [英] "cannot find macro" error in the macro's own doc test

查看:54
本文介绍了“找不到宏"宏自己的文档测试中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

////用法://////```///让 x = addone!(100);///```#[宏_导出]宏规则!插件{($x:expr) =>($x + 1)}

如果我运行 cargo test,我得到

失败:---- src/lib.rs - addone (line 3) stdout ----错误:在此范围内找不到宏`addone!`-->src/lib.rs:2:9|2 |让 x = addone!(100);|^^^^^^

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

Rust 标准库中的宏遵循与上面代码相​​同的格式,所以我期待它可以工作.

解决方案

Doc 测试自动将代码块包装在 extern crate foo;fn main() { … } 如果他们在代码中没有找到这些元素,但是要获得导出的宏,您需要 extern 上的 #[macro_use] 属性crate foo;.

因此,你应该这样写:

////用法://////```///##[macro_use] extern crate foo;fn 主(){///让 x = addone!(100);///# }///```#[宏_导出]宏规则!插件{($x:expr) =>($x + 1)}

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

这在中有介绍Rust 编程语言,第一版.

至于 std,在所有缺少 #![no_std]#[macro_use] extern crate std;> crate 属性,所以它的宏可以立即生效.

I am trying to add documentation tests to a Rust macro that I'm exporting. Something like this:

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

If I run cargo test on this, I get

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);
  |         ^^^^^^

I can't think of a legal way of adding macro_use inside the doc test, so no luck there.

The macros in Rust's standard library follow the same format as the code above, so I was expecting it to work.

解决方案

Doc tests automatically wrap the code block in extern crate foo; fn main() { … } if they don’t find these elements in the code, but to get an exported macro you need the #[macro_use] attribute on the extern crate foo;.

Thus, you should write this:

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

(The lines prefixed with get hidden in the output, but included, sans the marker, in the code that gets compiled for the doc test.)

This is covered in The Rust Programming Language, first edition.

As for std, there is an implied #[macro_use] extern crate std; in all crates that lack the #![no_std] crate attribute, so its macros immediately work.

这篇关于“找不到宏"宏自己的文档测试中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆