如何在 Rust 中向宏文档添加示例?
How do I add examples to macro documentation in rust?
在写宏的时候,我想把它适当地记录下来,这包括示例。
但是当我尝试以与常规函数相同的方式执行此操作时,我得到:
[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]
}
如果这是正确的,就可以解释错误。
有什么方法可以实际向宏添加示例吗?
有可能,虽然有点绕;您需要按照以下方式进行操作:
/// # Example
/// ```
/// # #[macro_use] extern crate crate_name;
/// # fn main() {
/// use crate_name::module::object;
///
/// <example code>
/// # }
/// ```
#[macro_export]
macro_rules! some_macro {
<macro code>
}
在写宏的时候,我想把它适当地记录下来,这包括示例。
但是当我尝试以与常规函数相同的方式执行此操作时,我得到:
[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]
}
如果这是正确的,就可以解释错误。
有什么方法可以实际向宏添加示例吗?
有可能,虽然有点绕;您需要按照以下方式进行操作:
/// # Example
/// ```
/// # #[macro_use] extern crate crate_name;
/// # fn main() {
/// use crate_name::module::object;
///
/// <example code>
/// # }
/// ```
#[macro_export]
macro_rules! some_macro {
<macro code>
}