22 Writing your own macros

 

This chapter covers

  • Why macros exist
  • Understanding and writing basic macros
  • Learning to read macros written by others
  • Using macros to reduce code duplication

It’s now time to learn how to write your own macros. Writing macros can be pretty complicated, which is why they are here near the very end of the book. You very rarely need to write them, but sometimes you might want to because they are very convenient—they essentially write code for you. They have a syntax that is pretty different from normal Rust, and they take some getting used to. Well, a lot of getting used to.

Indeed, the book Programming Rust (O’Reilly, 2021) finishes its chapter on macros with a conclusion that sums up the feeling pretty well: “Perhaps, having read all this, you’ve decided that you hate macros.” Hopefully, that’s not the case with you, but we’ll see! Macros offer a power that nothing else can, and they begin to feel friendlier as you use them more and more. We'll start out with the case for macros and why they even exist in the first place.

22.1 Why macros exist

Macros are extremely common in Rust, as we have already noticed since the beginning of the book. Even println! itself is a macro. But we haven’t learned yet about what they are, besides mentioning in chapter 1 that a macro is like a function that writes code for you. This is actually a more important point than it might seem: a macro produces code before the compiler has even started looking at it.

22.2 Writing basic macros

22.3 Reading macros from the standard library

22.4 Using macros to keep your code clean

Summary