DEV Community

BC
BC

Posted on

Day32:macro_rules! - 100DayOfRust

We can use macro_rules to match a pattern and generate code.

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

macro_rules! test {
    ($left:expr; and $right:expr) => {
        println!("{:?} and {:?} is {:?}",
                 stringify!($left),
                 stringify!($right),
                 $left && $right)
    };

    ($left:expr; or $right:expr) => {
        println!("{:?} or {:?} is {:?}",
                 stringify!($left),
                 stringify!($right),
                 $left || $right)
    };
}

macro_rules! calculate {
    (eval $e:expr) => {
        let val: usize = $e; // Force types to be integers
        println!("{} = {}", stringify!{$e}, val);       
    };
}

fn main() {
    say_hello!();
    test!(1+1 == 2; and 2+2 == 4);
    test!(true; or false);
    calculate!(eval 1+2);
}
Enter fullscreen mode Exit fullscreen mode

Run it:

hello
"1 + 1 == 2" and "2 + 2 == 4" is true
"true" or "false" is true
1 + 2 = 3
Enter fullscreen mode Exit fullscreen mode

Another example:

use std::collections::HashMap;

macro_rules! map {
    () => {
        HashMap::new()
    }
}

fn main() {
    // use map! to make a new HashMap
    let mut m = map!();

    m.insert("Bo", 23);
    if let Some(age) = m.get("Bo") {
        println!("Age: {}", age);
    } else {
        println!("No key found");
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)