Summary

In this chapter, we covered the metaprogramming abilities of Rust and looked at many kinds of macros. The most frequently used macro is macro_rules!, which is a declarative macro. Declarative macros work at the abstract syntax tree level, which means that they do not support arbitrary expansions, but require that the macro expansions are well-formed in the AST. For more complex use cases, you can use procedural macros where you get complete control of manipulating the input and generating the desired code. We also looked at ways to debug macros using the cargo subcommand cargo-expand.

Macros are indeed a powerful tool, but not something that should be used heavily. Only when the more usual mechanisms of abstraction such as functions, traits, and generics do not suffice for the problem at hand should we turn to macros. Also, macros make the code less readable for newcomers to a code base and should be avoided. Having said that, they are quite useful in writing test case conditions and are widely used by developers.

In the next chapter, we'll get a glimpse of another side of Rust, the unsafe bits, which are less recommended but unavoidable if you want to interoperate Rust with different languages.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset