编写宏时,我想提出具体的文件,这包括例子 但是,当我尝试以与常规函数相同的方式执行此操作时,我得到:
[E0468]: an `extern crate` loading macros must be at the crate root
我每晚运行cargo test
来测试以下内容:
// src/lib.rs in crate with name advent9
/// this macro essentialy appends .as_bytes()
/// `b!("bla")` -> `"bla".as_bytes()`
///
/// # Examples
/// ```
/// #[macro_use]
/// extern crate advent9;
///
/// let bytes : &[u8] = b!("this is a bytestring");
///
/// println!("{:?}", bytes);
/// // prints:
/// // [116, 104, 105, 115, 32, 105, 115, 32, 97, 32, 98, 121, 116, 101, 115, 116, 114, 105, 110, 103]
/// ```
// I don't need this exported, but perhaps the example does?
#[macro_export]
macro_rules! b {
($string:expr) => {
$string.as_bytes()
}
我对doctests的理解是每个都包含在他们自己的main
函数中。像这样:
fn main() {
#[macro_use]
extern crate advent9;
let bytes : &[u8] = b!("this is a bytestring");
println!("{:?}", bytes);
// prints:
// [116, 104, 105, 115, 32, 105, 115, 32, 97, 32, 98, 121, 116, 101, 115, 116, 114, 105, 110, 103]
}
如果这是正确的,它将解释错误。
有没有办法真正向宏添加示例?
答案 0 :(得分:1)
虽然有点复杂但有可能;你需要以下列方式做到这一点:
/// # Example
/// ```
/// # #[macro_use] extern crate crate_name;
/// # fn main() {
/// use crate_name::module::object;
///
/// <example code>
/// # }
/// ```
#[macro_export]
macro_rules! some_macro {
<macro code>
}