Chapter 22. Macros
A cento (from the Latin for “patchwork”) is a poem made up entirely of lines quoted from another poet.
Matt Madden
Rust supports macros, a way to extend the language in ways that go beyond what you can do with functions alone. For example, we’ve seen the assert_eq! macro, which is handy for tests:
assert_eq!(gcd(6,10),2);
This could have been written as a generic function, but the assert_eq! macro does several things that functions can’t do. One is that when an assertion fails, assert_eq! prints an error message using a format string that the user can provide by passing extra arguments to the macro. Functions in Rust can’t take a variable number of arguments. Macros can, because the way they work is completely different.
Macros are a kind of shorthand. During compilation, before types are checked and long before any machine code is generated, each macro call is expanded—that is, it’s replaced with some Rust code. The preceding macro call expands to something ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access