Skip to Content
Programming Rust, 2nd Edition
book

Programming Rust, 2nd Edition

by Jim Blandy, Jason Orendorff, Leonora F. S. Tindall
June 2021
Intermediate to advanced
738 pages
18h 47m
English
O'Reilly Media, Inc.
Content preview from Programming Rust, 2nd Edition

Chapter 21. 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! generates an error message containing the filename and line number of the assertion. Functions have no way of getting that information. 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 roughly like this:

match (&gcd(6, 10), &2) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            panic!("assertion failed: `(left == right)`, \
                    (left: `{:?}`, right: `{:?}`)", left_val, right_val);
        }
    }
}

panic! is also a macro, which itself expands to yet more Rust code (not shown here). That code uses two other macros, file!() and line!(). Once every macro call in the crate is fully expanded, Rust moves on to the next phase of compilation.

At run time, an assertion failure would look like this (and would indicate a bug in ...

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.
Start your free trial

You might also like

The Rust Programming Language, 2nd Edition

The Rust Programming Language, 2nd Edition

Steve Klabnik, Carol Nichols

Publisher Resources

ISBN: 9781492052586Errata PageSupplemental Content