Skip to Content
Programming Rust
book

Programming Rust

by Jim Blandy, Jason Orendorff
December 2017
Intermediate to advanced content levelIntermediate to advanced
619 pages
15h 11m
English
O'Reilly Media, Inc.
Content preview from Programming Rust

Chapter 20. Macros

A cento (pronounced “cento,” from the Latin for “patchwork”) is a poem made up entirely of lines quoted from another poet.

Matt Madden

Your quote here.

Bjarne Stroustrup

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 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, so it then expands to some more Rust code. 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 ...

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

The Rust Programming Language

Steve Klabnik, Carol Nichols
Programming Rust, 2nd Edition

Programming Rust, 2nd Edition

Jim Blandy, Jason Orendorff, Leonora F. S. Tindall
The Rust Programming Language, 2nd Edition

The Rust Programming Language, 2nd Edition

Steve Klabnik, Carol Nichols

Publisher Resources

ISBN: 9781491927274Errata PageSupplemental Content