Macros

What are macros? When we see a "function" with an exclamation point in its name like println!, format!, and dbg!, we know it is not actually a function, but a macro.

Macros are how we do metaprogramming in Rust. A metaprogram is a program that generates a program. In Perl, we do this with things like source filters, Devel::Declare, Moose, and eval. In Rust, we have macros.

Macros are not Rust code, per se. Rather, they generate Rust code. They happen before the compiler gets to see the code. As such, they can do things that functions can't. For example, you may have noticed that println! is variadic. We've already called it with one, two, and three arguments.


#![allow(unused_variables)]
fn main() {
println!("Hello, World!");
println!("Hello, {}!", name);
println!("Hello, {} {}!", salutation, name);
}

You may not have noticed, because that's normal for Perl. But Rust does not have variadic functions. We couldn't make a println function like this. But we can do it with a macro.

There's a lot more to macros, but for now it's probably enough to know that the exclamation mark indicates we're looking at a macro rather than a function. Sort of like the sigils in Perl!