Jon Gjengset explains Rust's declarative macros by re-implementing the vec! macro from the standard library.
In this second Crust of Rust video, we cover declarative macros, macro_rules!, by re-implementing the vec! macro from the standard library. As part of that, we cover not only how to write these, but some of the gotchas and tricks you'll run into, and some common use-cases.
You can find the final code at gist.github.com/jonhoo/ec57882a976a2d2a92b3138ea25cd45a, and the Little Book of Rust Macros at danielkeep.github.io/tlborm/book/index.html.
Introduction
The vec macro
The Little Book of Rust Macros
Macro syntax and hygiene
The empty vector
Non-empty vectors
Macros v2
Macro delimiters
Declarative vs procedural macros
Repeated macro arguments
Trailing commas
Why are macros useful?
Vector by repetition
Macro rules readability
Invalid macro inputs
Test that something doesn't compile
Tidying up the patterns
Reallocations for repetition constructor
Macro argument trait bounds
"use" hygiene in macros
The standard library pattern
The need for counting
Eager macro errors
Counting in macros
Other ways of counting
Ensuring count is computed at compile time
Hiding internal macro patterns
Other collection literals
Comparing against the std implementation
You can watch the live version with comments at youtube.com/watch?v=UIY75ohrqKQ
Why it's here
4 people recommend this
What people say. Recommended as an excellent explanation of Rust declarative macros.
4
u/420goonsquad420in r/rust • Recommends
On “Talk to me about macros”
…Rust proc macros are a whole different world. They let you execute arbitrary code at compile time, meaning you can make up syntax, run it through a proc macro, and have it spot out Rust code at the end. It's also how traits can be derived. Proc macros are magic.
If you want to learn more, I'd personally recommend Jon Gjengset's video(s) on them:
link to this videolink to this videolink to this video
Note that this is collectively about 10 hours of video, so buckle in.…
You might want to look into the "Crust of Rust" Youtube Playlist from Jon Gjengset. He has a video in there explaining Macros (\~1.5h), as well as two \~4h long Videos about them.
Generally, a great guy who puts out very good explanations.