2 Declarative macros
This chapter covers
- Writing declarative macros
- Avoiding boilerplate and duplication, implementing newtypes, writing simple domain specific languages, and composing functions
- Understanding the
lazy_static
crate
We will start this book in easy mode with declarative macros. These macros have a syntax that will immediately remind you of pattern matching, with a combination of matchers and transcribers. The matchers contain what you want to match against; the transcriber has the code you will generate when you find that match. It’s just that simple.
NOTE This chapter’s focus is a broad overview of declarative macros and their usage. This stands in contrast with the rest of this book, where we will focus on specific topics and a limited number of examples. The reason is that declarative macros are not the main focus of this book, and I expect the reader to know more about them than procedural macros. That means we can go through the subject of this chapter more quickly.
2.1 Creating vectors
But wait, this is an example-driven book! That means we should drag a first example into this. vec!
is used in several beginner’s explanations of declarative macros. We will go through a simplified implementation that shows how the aforementioned matchers and transcribers work together to generate the correct kind of code output for any given situation.