Today our focus is the derive_builder crate. It provides a macro to automatically generate setter methods for struct fields. And since all setters return the struct itself, we can chain them in a so called builder pattern.Continue reading »
Important note: this article is outdated! Go to http://zsiciarz.github.io/24daysofrust/ for a recent version of all of 24 days of Rust articles. The blogpost here is kept as it is for historical reasons.
In Rust there is no concept of a constructor as a language feature, like for example in C++. However there is a strong convention (and mentioned in the guidelines) to use a static method called
new as the constructor. This works well, but you can have only one function called
new in the
impl - there is no method overloading. So are we out of luck if we want to have different constructors? No! But arguably different purposes should imply different method names, so another convention is to prefix extra constructors with
with_ (such as Vec::with_capacity) or
from_, if the constructor does some kind of a conversion.