This chapter covers
- What metaprogramming is
- Metaprogramming in Rust
- When to use macros
- What this book will teach you
You are your own forerunner, and the towers you have builded are but the foundation of your giant-self. And that self too shall be a foundation.
-- Kahlil Gibran
Among the many powerful tools that Rust has to offer, macros are some of the most important and common. They serve as "a light in dark places, when all other lights go out", to be used when normal tools don’t suffice. That of itself is enough to make macros a core topic of this book. They have another neat quality though: they can be a "`pathway to many abilities`", as the emperor would put it. When you want to write a macro, you need knowledge of testing and debugging. You have to know how to set up a library because you cannot write a procedural macro without creating a library. Some knowledge about Rust internals, compilation, types, code organization, pattern matching, parsing… also comes in handy. Thus learning about macros allows me to talk about a variety of other programming topics! So we will be learning about Rust macros and using them to explore other subjects. Procedural macros, specifically, will take center stage because they are powerful and versatile… and you can already find a lot of useful content on declarative macros!
But we are getting ahead of ourselves. Let’s take a step back and start from the beginning.