1

在编写宏时,我想正确地记录它,这包括示例。
但是当我尝试以与常规函数相同的方式执行此操作时,我得到:

[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]
}

如果这是正确的,它将解释错误。

有什么方法可以将示例实际添加到宏中?

4

1 回答 1

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>
}
于 2017-12-30T12:40:09.137 回答