2017-12-30 57 views
0

マクロを書くとき、私はそれをproprerlyで文書化したいと思います。これには例が含まれています。
しかし、私は私が得る通常の関数と同じようにすることをやろう:マクロ文書の例を錆びさせる方法を教えてください。

[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() 
    } 

doctestをの私の理解がありますそれぞれ独自の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

私もR /錆/上のredditでこれを求めてきました:https://www.reddit.com/r/rust/comments/7n1c30/question_how_do_i_add_examples_to_macro/ – techhazard

答えて

0

少し複雑ですが、可能です。あなたは、以下の方法でそれを実行する必要があります。

/// # Example 
/// ``` 
/// # #[macro_use] extern crate crate_name; 
/// # fn main() { 
/// use crate_name::module::object; 
/// 
/// <example code> 
/// # } 
/// ``` 
#[macro_export] 
macro_rules! some_macro { 
    <macro code> 
} 
+0

ありがとうございました! – techhazard

関連する問題