There are actually two trade-offs:
- should the named setter accept
self
by value or reference?
- should the final
build
method accept self
by value or reference?
My recommendation is:
- mutable reference for the setters
- value for the
build
method
This differs slightly from the Builder Pattern presented in the Rust Book which uses a reference in build
.
Why passing by mutable reference for the setters?
While a compiler may optimize away the moves caused by a call to fn label(self, &str) -> ButtonBuilder
, it is not guaranteed.
On the other hand, the mutable reference way is already optimal so that you need not rely on the optimizer.
Why passing by value for the final build
?
For builders only composed of Copy
fields, there is no difference between build
taking self
or &self
.
However, as soon as the builder contains non-Copy
fields, passing &self
to build
requires deep-cloning these fields.
On the other hand, passing self
by value allows build
to move the fields, which avoid unnecessary copies.
If one wishes to re-use the builder, then the builder should implement Clone
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…