Builder
A builder is a type that collects optional fields and then builds the real value. In Rust it replaces default arguments and telescoping constructors.
Detailed Explanation
Rust has no default parameters. Session::new(token, user_id, ttl, flags, cookie) grows until nobody remembers the order. A builder is Session::builder().token("abc").ttl(30).build(). Required fields live on builder() or on build() as Result. Optional fields have defaults.
The typestate variant uses a generic parameter so build does not compile until required fields are set: Builder<MissingToken> has no build, and .token(...) returns Builder<HasToken>. That is compile-time completeness. The simpler variant stores Options and returns Err if a required field is missing. Start simple; typestate is for public APIs that have been misused.
Builders in Rust often take self by value on each setter so you can write a chain without mut, and they return Self. Or they take &mut self and you call build at the end. Both work. Consuming self prevents using a half-built builder twice by accident.
#[derive(Default)] plus struct update syntax, Session { token, ..Session::default() }, is a lighter builder for internal types with public fields. Use a real builder when fields are private or when construction can fail.
When you reach for a builder: many optional fields, or construction that needs validation. When you reach for new: two or three required arguments. When you reach for typestate: a public API where a missing field should be a compile error.
A builder that clones the world on every setter will show up in a profile. Take impl Into<String> and store it once. Take &str only if you will copy inside. Do not take String and also clone it "for safety". The builder owns the in-progress fields; build moves them into the product.
Code Examples
struct Session {
token: String,
ttl: u32,
}
struct SessionBuilder {
token: Option<String>,
ttl: u32,
}
impl SessionBuilder {
fn token(mut self, token: impl Into<String>) -> Self {
self.token = Some(token.into());
self
}
fn ttl(mut self, ttl: u32) -> Self {
self.ttl = ttl;
self
}
fn build(self) -> Result<Session, &'static str> {
Ok(Session { token: self.token.ok_or("token required")?, ttl: self.ttl })
}
}
fn main() {
let s = SessionBuilder { token: None, ttl: 30 }.token("abc").build().unwrap();
println!("{} {}", s.token, s.ttl); // prints: abc 30
}Common Gotchas
`build` that always `unwrap`s is a hidden panic
Return `Result` for missing required fields, or use typestate so `build` cannot be called early.
Consuming setters prevent reuse
`builder.token("a"); builder.token("b")` will not compile if setters take `self`. That is usually what you want.
`impl Into<String>` is friendly at the call site
Literals and `String`s both work. Do not take `String` only.
A builder is not `Default` on the product type
If `Session::default()` is invalid (empty token), do not derive `Default` on `Session`.