我正在尝试将文档测试添加到我要导出的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);
| ^^^^^^
我想不出一种macro_use
在doc测试中添加的合法方法,因此没有运气。
如果Doc测试在代码中extern crate foo; fn main() { … }
找不到这些元素,则会自动将代码块包装在其中,但是要获取导出的宏,您需要在上添加#[macro_use]
属性extern crate foo;
。
因此,您应该这样写:
/// Usage:
///
/// ```
/// # #[macro_use] extern crate foo; fn main() {
/// let x = addone!(100);
/// # }
/// ```
#[macro_export]
macro_rules! addone {
($x:expr) => ($x + 1)
}
(以前缀的行在#
输出中隐藏,但在为文档测试编译的代码中没有标记,但包含在内)。
Rust编程语言第一版对此进行了介绍。
至于std
,则#[macro_use] extern crate std;
在所有未定义#![no_std]
crate属性的板条箱中都有一个隐含内容,因此其宏可立即使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句