Builder pattern

The builder pattern is a design pattern to mimic named, optional function arguments. This is done by building a struct containing all available parameters, which can be modified by chaining method calls.

Because using the builder pattern can lead to a lot of repetitive code, there are procedural macro crates to make the code shorter and more declarative.

Example
Let's make a simple builder pattern to build an SQL query. It can be used like this:

Each parameter has its own method. Because of the method chaining, it looks concise and readable. All parameters are optional, except the one passed to the function, because it is required in order to obtain a  value.

Note that if the method is called multiple times, the conditions should be combined, not replaced. Also note that the method has two parameters, which could be represented in the builder struct as two fields, or as a tuple.

This is how the builder type could be written:

To create a value of this type, the function initializes the  field with its parameter. All other fields are initialized with default values:

The methods that modify the struct fields return the struct to allow chaining. They can accept either by value or by reference. Taking by value means that the struct update syntax can be used, whereas accepting  means that a builder can be used multiple times (unless the  method consumes the struct).

Here we go with the easier solution, which is taking by value:

This builder can now be used. It will panic, because the conversion to a isn't implemented, but it compiles.