For a Rust ServerConfig with a dozen optional settings, why use a builder instead of new() with Option parameters, and how should the builder be shaped?
answer
- anonymous Some and None
- a separate type, chained calls
- one terminal method validates
- self by value or &mut self
- an attribute against dropped builders
basics
~20 sA builder replaces positional Some/None arguments with named, chained setters and one terminal build() that validates settings together and returns Result. Setters take and return self by value or &mut self, and #[must_use] warns when a configured builder is discarded.
solid answer
~40 sA `new` with a dozen `Option` parameters gives unreadable call sites, lets same-typed arguments be swapped silently, and breaks every caller when a setting is added. A builder fixes all three: `ServerConfigBuilder` takes only required values in its constructor, offers one chained setter per option, and ends in `build() -> Result<ServerConfig, ConfigError>`, which fills defaults and checks cross-field rules. Setters either consume and return `self`, like `std::thread::Builder`, or take and return `&mut Self`, like `std::process::Command`; the second shape fails with E0716 if you bind `let b = Builder::default().port(8080);` and use `b` later. Marking a consuming builder `#[must_use]` makes rustc warn on `b.port(8080);`, which otherwise silently drops the configured builder.
code
rust · 38 linesuse std::time::Duration;
#[derive(Debug)]
struct ServerConfig { port: u16, workers: usize, timeout: Duration, tls: bool }
#[derive(Debug, PartialEq)]
enum ConfigError { TlsNeedsSecurePort }
#[must_use = "a builder does nothing until build() is called"]
#[derive(Debug, Default)]
struct ServerConfigBuilder { port: Option<u16>, workers: Option<usize>, timeout: Option<Duration>, tls: bool }
impl ServerConfigBuilder {
fn port(mut self, port: u16) -> Self { self.port = Some(port); self }
fn workers(mut self, n: usize) -> Self { self.workers = Some(n); self }
fn timeout(mut self, t: Duration) -> Self { self.timeout = Some(t); self }
fn tls(mut self, on: bool) -> Self { self.tls = on; self }
fn build(self) -> Result<ServerConfig, ConfigError> {
let port = self.port.unwrap_or(8080);
if self.tls && port == 80 {
return Err(ConfigError::TlsNeedsSecurePort);
}
Ok(ServerConfig {
port,
workers: self.workers.unwrap_or(4),
timeout: self.timeout.unwrap_or(Duration::from_secs(30)),
tls: self.tls,
})
}
}
fn main() {
let cfg = ServerConfigBuilder::default().port(8443).tls(true).build();
println!("{cfg:?}");
let bad = ServerConfigBuilder::default().port(80).tls(true).build();
assert_eq!(bad.unwrap_err(), ConfigError::TlsNeedsSecurePort);
}go deeper
Recall what a builder looks like: a separate type with chained setter methods and a final build() call that returns the configured value.
Explain the two setter shapes, self by value and &mut self, and which std types use each, plus why a long list of Option parameters reads badly.
Diagnose the traps: E0716 from binding a borrow of a temporary builder, a consuming builder silently dropped without #[must_use], and validation placed in build() returning Result rather than panicking.
Weigh a builder against a public-field struct with Default: the builder keeps fields private and validates, but triples the code per option and fixes the error type into the public API.
## Why positional Options stop scaling A `ServerConfig` with a dozen optional settings could take them all in `new`: ```rust let cfg = ServerConfig::new(Some(8443), None, None, Some(true), None, Some(64)); ``` Three problems appear at once: - **Unreadable call sites.** Nothing says which `None` is the timeout and which is the TLS certificate path; two `Option<u16>` parameters can be swapped without a compile error. - **Every new setting is a breaking change.** Adding a thirteenth parameter changes the signature, so every caller must be edited. - **Validation is awkward.** Settings that depend on each other end up checked in a function whose arguments are anonymous. A lighter alternative is a struct with public fields and `ServerConfig { port: 8443, ..Default::default() }`. It reads well, but every field must be public (a private field makes that literal fail with E0451 outside the module), and nothing validates the combination. ## The shape of a builder The Rust API Guidelines (C-BUILDER) describe the pattern in four parts, shown here with common practice filled in: 1. A separate type, `ServerConfigBuilder`, holds the configuration as it is collected, usually as `Option` fields; it often derives `Default`. 2. The builder's constructor takes only what is **required** to build a `ServerConfig`, so a missing required value is a compile error rather than a run-time one. 3. One chained setter per option, each returning the builder. 4. One or more **terminal** methods, typically `build()`, that produce the final value. A strong `build()` returns `Result<ServerConfig, ConfigError>`: it fills unset options with their defaults (`self.port.unwrap_or(8080)`) and checks cross-field rules, such as TLS on a plain-HTTP port, in one place. ## Consuming or non-consuming setters Setters come in two ownership shapes, and std uses both: | | Consuming | Non-consuming | |---|---|---| | Setter signature | `fn port(mut self, p: u16) -> Self` | `fn port(&mut self, p: u16) -> &mut Self` | | Terminal method | takes `self` | takes `&self` or `&mut self` | | std example | `std::thread::Builder` | `std::process::Command`, `std::fs::OpenOptions` | | One-liner chain | works | works within one statement | | Conditional setting | reassign: `b = b.tls(true);` | `if tls { b.tls(true); }` | | Main trap | a discarded result drops the builder | a temporary dropped while borrowed | A consuming setter **moves** the builder in and out; it does not clone heap data. The guidelines prefer a non-consuming builder when building does not need to own the configuration, and a builder whose terminal method must take ownership should make every setter take and return `self`. The non-consuming trap is **E0716**. `let b = ServerConfigBuilder::default().port(8080);` creates a temporary builder, borrows it for `port`, and binds `b` to that borrow; the temporary is freed at the end of the statement, so the next use of `b` fails with "temporary value dropped while borrowed". The fix is to bind the builder first: `let mut b = ServerConfigBuilder::default(); b.port(8080);`. ## #[must_use] on the builder With consuming setters, the statement `b.port(8080);` moves `b` into `port`, and the configured builder that comes back is dropped on the spot. rustc 1.99 says nothing about this unless the type or the method is marked **`#[must_use]`**; with the attribute it warns "unused `ServerConfigBuilder` that must be used" under the `unused_must_use` lint. std does this on `std::thread::Builder`, declared `#[must_use = "must eventually spawn the thread"]`. A reason string after `=` is shown in the warning, so write one that tells the caller what to do. ## What a builder does not give you - **No compile-time check of required settings beyond the constructor.** If a value is required but set by a setter, forgetting it is caught only in `build()`. Encoding "set" and "not set" in the type system is the typestate builder, covered in the material on const parameters and typestate. - **More code.** Each option appears in the target struct, the builder and a setter. For a handful of settings, a constructor or a public-field struct with `Default` is simpler. - **Error type design.** `build()` needs an error enum that names each failed check, so callers can report it. The interview answer that lands names the readability and compatibility costs of positional `Option` parameters, sketches the builder with a validating `build() -> Result`, and explains the consuming versus `&mut` choice with its trap.
- Why does let b = ServerConfigBuilder::default().port(8080); fail when port takes and returns &mut Self?`ServerConfigBuilder::default()` is a temporary; `port` borrows it mutably and returns that borrow, which `b` stores. The temporary is freed at the end of the `let` statement, so any later use of `b` fails with E0716, "temporary value dropped while borrowed". Bind the builder first, `let mut b = ServerConfigBuilder::default();`, then call `b.port(8080);`.
- What happens when a caller writes b.port(8080); with a consuming builder?`port` takes `b` by value, so `b` is moved and unusable afterwards; the configured builder it returns is dropped immediately because the statement ignores it. Without `#[must_use]` rustc 1.99 compiles this silently. With `#[must_use]` on the type it warns "unused `ServerConfigBuilder` that must be used". The fix is `b = b.port(8080);`.
- How can a builder make a forgotten required setting a compile error?Take required values as parameters of the builder's own constructor, as the API Guidelines advise, so `ServerConfigBuilder::new(bind_addr)` cannot be called without one. Setters then cover only optional settings. Tracking set and unset fields in the builder's type parameters is the typestate builder, a separate technique with more code.
- Consuming setters clone the builder's heap data on every call.
- rustc always warns when a consuming setter's returned builder is discarded, even without #[must_use].
- Adding an Option parameter to new() is a non-breaking change for existing callers.
- With &mut self setters, let b = Builder::default().port(8080); and later calls on b compile fine.
- A builder cannot check settings that depend on each other until the server is running.