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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With