This system of macros has existed as part of Rust since pre- 1.0 releases. These macros are defined using a macro called macro_rules!. Let's look at an example:
// chapter2/syntactic-macro.rsmacro_rules! factorial { ($x:expr) => { { let mut result = 1; for i in 1..($x+1) { result = result * i; } result } };}fn main() { let arg = std::env::args().nth(1).expect("Please provide only one argument"); println!("{:?}", factorial!(arg.parse::<u64>().expect("Could not parse to an integer")));}
We start with defining the factorial macro. Since we do not want the compiler to refuse to compile our code as it might overflow the macro stack, we will use a non-recursive implementation. A syntactic macro in Rust is a collection of rules ...