Something derive-type macros already show us is that we can generate entire trait implementations using macros. Similarly, we can generate entire structs and functions using macros and avoid copy-and-paste programming, as well as tedious boilerplate code. Since macros are executed right before compilation, the generated code will be checked accordingly while avoiding the details of strictly typed languages. Let's see how!
Code generation using macros
How to do it...
Code generation can be as easy as these few steps:
- Run cargo new code-generation --lib in Terminal (or PowerShell on Windows) and open the directory with Visual Studio Code.
- Open src/lib.rs and add the first simple macro:
// Repeat the statement that was...