Sub topic 16
The builder pattern
This chapter assumes you know how to define a struct, write impl blocks, and tell self, &self, and &mut self apart. It also assumes you can read Result and match. If method receivers are still unclear, review them first, because the whole pattern depends on them.
The problem a builder solves
Rust has no default arguments and no function overloading. A constructor such as Server::new(host, port, max_connections, timeout, tls) is hard to read at the call site, because five positional values tell you nothing about their meaning. Adding a field later breaks every caller.
A builder is a separate struct that collects settings one call at a time. A final build method turns it into the real value. The call site then names each setting:
let server = ServerBuilder::new("localhost").port(8080).build();The pattern combines three things from earlier chapters: an associated function as the entry point, self receivers for chaining, and private fields so that callers must go through the builder.
The consuming builder
In this version, each setter takes self by value, changes it, and returns it. The builder moves through the chain and build consumes it.
#[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 are worth noting:
- The parameter is
mut self, not&mut self. Themutmakes the owned local binding mutable. It does not make the caller's variable mutable, because the caller gave up the value. newsupplies defaults for optional settings. Here the port defaults to 80.buildmovesself.hostout of the builder. That is legal becausebuildowns the builder and nothing uses it afterward. A&selfreceiver would force a.clone().
Validating in build
A builder is the natural place to enforce rules that a plain struct literal cannot. Make build return a Result, so invalid combinations never become a Server.
#[derive(Debug)]
struct Server {
host: String,
port: u16,
max_connections: u32,
}
#[derive(Debug, PartialEq)]
enum BuildError {
EmptyHost,
ZeroConnections,
}
struct ServerBuilder {
host: String,
port: u16,
max_connections: u32,
}
impl ServerBuilder {
fn new(host: &str) -> Self {
Self {
host: host.to_string(),
port: 80,
max_connections: 100,
}
}
fn port(mut self, port: u16) -> Self {
self.port = port;
self
}
fn max_connections(mut self, n: u32) -> Self {
self.max_connections = n;
self
}
fn build(self) -> Result<Server, BuildError> {
if self.host.is_empty() {
return Err(BuildError::EmptyHost);
}
if self.max_connections == 0 {
return Err(BuildError::ZeroConnections);
}
Ok(Server {
host: self.host,
port: self.port,
max_connections: self.max_connections,
})
}
}
fn main() {
let good = ServerBuilder::new("localhost")
.port(8080)
.max_connections(500)
.build();
println!("{:?}", good);
let bad = ServerBuilder::new("").build();
println!("{:?}", bad);
}Validation at the end, rather than in each setter, lets callers set fields in any order. It also lets you check rules that involve several fields at once.
Required and optional settings
Put required values in new, as host is above. Put optional values in setters with defaults. If a required value cannot be a constructor argument, store it as an Option in the builder and return an error variant such as MissingHost from build when it is still None.
The borrowing builder
The second style uses &mut self setters that return &mut Self. This lets you keep the builder and call build more than once.
#[derive(Debug)]
struct Request {
url: String,
headers: Vec<(String, String)>,
}
struct RequestBuilder {
url: String,
headers: Vec<(String, String)>,
}
impl RequestBuilder {
fn new(url: &str) -> Self {
Self {
url: url.to_string(),
headers: Vec::new(),
}
}
fn header(&mut self, key: &str, value: &str) -> &mut Self {
self.headers.push((key.to_string(), value.to_string()));
self
}
fn build(&self) -> Request {
Request {
url: self.url.clone(),
headers: self.headers.clone(),
}
}
}
fn main() {
let mut builder = RequestBuilder::new("https://example.com");
builder.header("Accept", "text/html").header("X-Id", "7");
let first = builder.build();
builder.header("X-Extra", "1");
let second = builder.build();
println!("{:?}", first);
println!("{:?}", second);
}build must clone, because it only borrows the builder. That is the cost of reuse.
Comparing the two styles
| Aspect | Consuming (`self`) | Borrowing (`&mut self`) |
|---|---|---|
| Setter signature | `fn f(mut self, ..) -> Self` | `fn f(&mut self, ..) -> &mut Self` |
| `build` signature | `fn build(self) -> T` | `fn build(&self) -> T` |
| Moves fields into the result | Yes, no clones | No, must clone |
| Builder reusable after `build` | No | Yes |
| One-expression `let x = B::new().a().build();` | Works | Works |
| `let b = B::new().a();` then use `b` | Works | Fails to compile |
| Setting fields conditionally | Must reassign: `b = b.a();` | Call `b.a();` on a `mut` binding |
The standard library uses both. std::process::Command is a borrowing builder. std::thread::Builder is a consuming one.
Common errors
Using a builder after it moved
With a consuming builder, every setter call moves the value. Code such as this fails with "use of moved value":
let b = ServerBuilder::new("localhost");
let b2 = b.port(9000);
let b3 = b.port(9001); // error: `b` was moved by the previous callIf you need conditional settings, shadow or reassign the binding:
let mut b = ServerBuilder::new("localhost");
if use_alt_port {
b = b.port(9000);
}Dropping a temporary too early
With a borrowing builder, this fails with "temporary value dropped while borrowed":
let b = RequestBuilder::new("https://example.com").header("A", "1");The RequestBuilder is a temporary that is destroyed at the end of the statement. The &mut Self that header returned would then point at nothing. Either finish the chain in one statement, ending in build(), or bind the builder first and call header in a separate statement.
Letting callers skip the builder
If Server has public fields, callers can write a struct literal and bypass your validation. Keep the target struct's fields private, and put the builder in the same module so it can construct the struct. Callers in other modules then have no way to build a Server except through build.
Forgetting to mark the result as important
If a consuming setter returns Self and the caller ignores it, the change is silently lost. This line compiles but does nothing useful:
builder.port(8080);Add #[must_use] to the builder struct so the compiler warns about this.
#[must_use]
struct ServerBuilder {
host: String,
port: u16,
}When not to use a builder
- A struct with two or three fields and no invariants is clearer with a plain literal or
new. - If every field has a sensible default and you only want to override a few, struct update syntax with
..Default::default()is shorter, and it needs no extra type. - If you only validate one field, a single constructor returning
Resultis enough.
A builder pays off when there are many optional settings, when validation spans several fields, or when you want to add settings later without breaking callers.
Exercise
You wrote a consuming builder whose build(self) -> Server moves self.host into the result. A teammate wants to call build twice on the same builder to make two servers. Which two changes make that compile, and what does each cost?
Show answer
Option 1: change the setters to &mut self -> &mut Self and build to &self, cloning the fields inside build. The cost is a clone of each owned field on every build. Option 2: keep the consuming builder and derive Clone on it, so callers write builder.clone().build(). The cost is a clone at the call site, which callers must remember, but the builder code stays unchanged and build still avoids cloning.
Exercise
Extend ServerBuilder from the validation section with a timeout_secs(mut self, secs: u32) -> Self setter, defaulting to 30 in new. Add a rule to build that returns BuildError::BadTimeout when the value is 0. What changes are needed outside build and the setter?
Show answer
Add a timeout_secs: u32 field to both Server and ServerBuilder. Set it to 30 in new. Add the BadTimeout variant to BuildError. In build, add if self.timeout_secs == 0 { return Err(BuildError::BadTimeout); } and copy the field into Server. Existing callers keep compiling unchanged, because the new setting is optional with a default.