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

前端 未结 1 1704
予麋鹿
予麋鹿 2021-01-11 10:13

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

/// Usage:
///
/// ```
/// let x = addone!(100);
/// ```
#[m         


        
相关标签:
1条回答
  • 2021-01-11 10:36

    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.

    0 讨论(0)
提交回复
热议问题