Sub topic 16
The builder pattern
This chapter assumes you know how to define structs, write impl blocks, and use self, &self, and &mut self receivers. It also assumes you understand moves and basic privacy rules.
Why a builder
A constructor like Server::new(host, port, timeout, tls) gets hard to read as options grow. Rust has no default or named arguments, so callers must pass every value in order. A builder is a second struct that collects settings step by step. A final build call turns it into the real value.
The consuming builder
The builder below stores the settings. Each setter takes self by value, changes it, and returns it. That lets calls chain.
#[derive(Debug)]
struct Server {
host: String,
port: u16,
}
struct ServerBuilder {
host: String,
port: u16,
}
impl ServerBuilder {
fn new(host: &str) -> Self {
Self {
host: host.to_string(),
port: 80,
}
}
fn port(mut self, port: u16) -> Self {
self.port = port;
self
}
fn build(self) -> Server {
Server {
host: self.host,
port: self.port,
}
}
}
fn main() {
let server = ServerBuilder::new("localhost").port(8080).build();
println!("{:?}", server);
}Three details matter here:
newis an associated function. It sets the required value (host) and a default for the optional one (port).porttakesmut self. Themutapplies to the local binding inside the method. The caller does not need amutvariable.buildtakesself, so the builder is consumed and cannot be reused afterward.
Consuming versus borrowing setters
Setters can also take &mut self and return &mut Self. That style lets you keep the builder and call build more than once, but build then has to clone or copy the fields. The trade-off:
| Style | Setter signature | Chaining on a temporary | Reuse after build |
|---|---|---|---|
| Consuming | `fn port(mut self, p: u16) -> Self` | Works | No, it is moved |
| Borrowing | `fn port(&mut self, p: u16) -> &mut Self` | Fails if you store the result | Yes |
With a borrowing builder, let b = Builder::new().port(1); fails to compile. The temporary created by new() is dropped at the end of the statement, while b still borrows it. The consuming style avoids this problem, so it is the usual choice for simple builders.
Common errors
- Use after move. Calling
builder.port(1)and thenbuilder.build()fails whenporttakesself. Rebind the result:let builder = builder.port(1);. - Forgetting to return
self. A setter that ends withself.port = port;and noselfreturns(), so the next call in the chain fails. - Required fields. If a field has no sensible default, make it a parameter of
new, or havebuildreturnResult<Server, String>and validate there.
Exercise
Why does fn build(self) -> Server take self by value instead of &self?
Show answer
Taking self moves the builder's fields, such as the String host, into the Server without cloning them. It also consumes the builder, so it cannot be used again by mistake. With &self, build would have to clone the String.
Exercise
Add a host setter to ServerBuilder that follows the same consuming style, so ServerBuilder::new("a").host("b").build() yields host "b".
Show answer
fn host(mut self, host: &str) -> Self { self.host = host.to_string(); self }