8 Builder with attributes
This chapter covers
- Working with field-level custom attributes to rename methods
- Using root-level custom attributes to decide on error handling
- Making a builder easier to use with type state
- Exploring how derive and attribute macros differ
- Parsing (document) attributes inside function-like macros
Every macro we created thus far had its behavior set in stone. Nothing was customizable. But sometimes you want overridable behavior, because that greatly increases flexibility, or you may need it to meet some requirements. In this chapter, we focus on customization via attributes, which are available for both derive and attribute macros. We will see how we can add information to a macro attribute and other parts of your code, like the individual properties of a struct.
As always, we need a project to illustrate these possibilities. Instead of introducing something new, let’s save some time by expanding on the builder example we created previously. How can we make it more versatile? Perhaps we can start by allowing users to rename the setter methods that will appear on our builder. This is quite typical functionality (Serde, for example, allows renames), because sometimes there is a mismatch between what your data looks like and what you need it to be to conform to standards or requirements. Even if the default works for most cases, it’s something you may want to make possible.