“cannot find macro” error in the macro's own doc test

好久不见. 提交于 2020-05-08 06:38:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/31644207/cannot-find-macro-error-in-the-macros-own-doc-test

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!