[Rust] Write macro

Define a macro and use it:

macro_rules! my_macro {
    () => {
        println!("Check out my macro!");
    };
}

fn main() {
    my_macro!();
}

 

Notice that you have time define macrobefore main function. Otherwise it doesn't work.

 

Expose a macro from module:

mod macros {
    #[macro_export]
    macro_rules! my_macro {
        () => {
            println!("Check out my macro!");
        };
    }
}

fn main() {
    my_macro!();
}

We need to add attribute #[macro_export], in order to make it work.

 

Arms:

The macro my_macro is defined with two "arms", each of which matches different patterns of input and associates those patterns with specific code blocks.

There are two arms in following code:

macro_rules! my_macro {
    () => {
        println!("Check out my macro!");
    }; // ; is important
    ($val:expr) => { //:expr the val should be an expersion
        println!("Look at this other macro: {}", $val);
    }; // ; is important
}

fn main() {
    my_macro!();
    my_macro!(7777);
}

 

posted @ 2024-02-27 15:23  Zhentiw  阅读(11)  评论(0)    收藏  举报