Rust 1.7.0 macro宏的復用 #[macro_use]的使用方法


Rust 1.7.0 中的宏使用范圍包含三種情況:
第一種情況是宏定義在當前文件里。這個文件可能是 crate 默認的 module,也可能是隨意的 module 模塊。
另外一種情況是宏定義在當前 crate 。可是不是在當前文件里,而是其它 module 模塊中。
第三種情況是宏定義在其它的 crate 中。或者其它的 crate 子模塊中。

使用#[macro_use] 能夠使被注解的module模塊中的宏應用到當前作用域中。或者凝視crate中的宏應用到當前crate作用域中。

第一種情況的樣例:

macro_rules! say_hello{
   ()=>(
       println!("Hello");
   )
}

fn main(){
    say_hello!();
}

另外一種情況:

  • 先創建一個新文件 macros.rs ,定義一個宏 say_bonjour
macro_rules! say_bonjour{
   ()=>(
       println!("Bonjour");
   )
}
  • 使用
#[macro_use]
pub mod macros;

macro_rules! say_hello{
   ()=>(
       println!("Hello");
   )
}

fn main(){
    say_hello!();
    say_bonjour!();
}
  • 假設沒有 #[macro_use] 編譯會出現

    error: macro undefined: ‘say_bonjour!’

第三種情況:凝視在外部 crate 的語句

  1. 創建 log 項目

    cargo new log
    
  2. 在 log 項目中,lib.rs 是入口,在lib.rs中定義 macors 模塊。

. . . #[macro_use] mod macros; . . .

然后,創建相應mod macros 的 macros.rs 文件 vi src/macros.rs
聲明宏 log、error、warn、info,在每一個宏定義前面加入 #[macro_export]凝視。表示這些宏能夠被外部的 crate 使用。

.
.
.
#[macro_export]
macro_rules! log {
    ...
}

#[macro_export]
macro_rules! error {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::LogLevel::Error, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::LogLevel::Error, $($arg)*);
    )
}

#[macro_export]
macro_rules! warn {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::LogLevel::Warn, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::LogLevel::Warn, $($arg)*);
    )
}


#[macro_export]
macro_rules! info {
    (target: $target:expr, $($arg:tt)*) => (
        log!(target: $target, $crate::LogLevel::Info, $($arg)*);
    );
    ($($arg:tt)*) => (
        log!($crate::LogLevel::Info, $($arg)*);
    )
}


.
.
.

使用:引入 log crate的時候,注明#[macro_use]

#[macro_use]
extern crate log;

.
.
.

if !shutdown.load(Ordering::SeqCst) {
                        info!("ConnectionHandler: read timed out ({:?}). Server not shutdown, so \ retrying read.",
                              err);
                        continue;
                    } else {
                        info!("ConnectionHandler: read timed out ({:?

}). Server shutdown, so \ closing connection.", err); break; } . . .


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM