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);
}
Run it:
hello
"1 + 1 == 2" and "2 + 2 == 4" is true
"true" or "false" is true
1 + 2 = 3
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");
}
}
Top comments (0)