Macros in Rust and their types

Rust macros do their magic of code generation before the program compiles to a binary object file. They take input, known as token trees, and are expanded at the end of the second pass of parsing during Abstract Syntax Tree (AST) construction. These are pieces of jargon from the compiler world and need some explanation, so let's do that. To understand how macros work, we need to be familiar with how source code is processed by the compiler to understand a program. This will help us in understanding how a macro processes its input and the error messages they emit when we use them incorrectly. We'll only cover parts that are relevant to our understanding of macros.

First, the compiler reads the source code byte ...

Get Mastering Rust - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.