Builder Pattern
Build complex configuration or domain objects step-by-step with defaults, fluent setters, and validation in build().
Busca en todas las páginas de la documentación
Build complex configuration or domain objects step-by-step with defaults, fluent setters, and validation in build().
let client = HttpClient::builder()
.timeout(Duration::from_secs(10))
.build()?;When to reach for this: Many optional fields or validation that should run once at construction.
#[derive(Default)]
struct ConfigBuilder {
port: Option<u16>,
host: Option<String>,
}
impl ConfigBuilder {
pub fn port(mut self, port: u16) -> Self { self.port = Some(port); self }
pub fn host(mut self, host: impl Into<String>) -> Self { self.host = Some(host.into()); self }
pub fn build(self) -> Result<Config, &'static str> {
Ok(Config {
port: self.port.ok_or("port required")?,
host: self.host.unwrap_or_else(|| "localhost".into()),
})
}
}What this demonstrates:
Config is public after successful buildbuild() returns Result for validation errorsself methodsDerive with typed-builder or bon for large structs. For async clients, builder might produce Client that connects on build().await.
mut self chain without cloning strings until build.| Alternative | Use When | Don't Use When |
|---|---|---|
Config::from_env | 12-factor apps | Library API |
| Struct literal | ≤3 fields | Many optional fields |
serde + validate | File-based config | Programmatic construction |
Default gives empty object; builder adds validation and staged setup.
build(self) -> impl Future<Output = Result<Client>> for connection setup.
Option in builder until build(); or separate new(required) + optional setters.
Flatten clap args into builder or build Config from matches.
ConfigBuilder::default().port(0).build().unwrap() in tests.
Compile-time phase separation; see typestate pattern.
Regenerate on field changes; review generated API surface.
&mut self setters if sharing builder across threads (rare).
Do not expose half-built product; only build() returns product.
Usually order-independent; document if setters interact.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026