Builder Pattern Rust Typed
Implement a typed builder pattern for constructing complex objects with validation.
Code
pub struct HttpRequest {
method: String,
url: String,
headers: Vec<(String, String)>,
}
pub struct HttpRequestBuilder {
method: Option<String>,
url: Option<String>,
headers: Vec<(String, String)>,
}
impl HttpRequestBuilder {
pub fn new() -> Self { Self { method: None, url: None, headers: Vec::new() } }
pub fn method(mut self, m: &str) -> Self { self.method = Some(m.to_string()); self }
pub fn url(mut self, u: &str) -> Self { self.url = Some(u.to_string()); self }
pub fn header(mut self, k: &str, v: &str) -> Self { self.headers.push((k.to_string(), v.to_string())); self }
pub fn build(self) -> Result<HttpRequest, String> {
Ok(HttpRequest {
method: self.method.ok_or("method required")?,
url: self.url.ok_or("url required")?,
headers: self.headers,
})
}
}What the code does
The working surface is the functions new, method, url and header — everything else is wiring.
Result is the error channel: the caller receives the failure as a value instead of an exception.
What to watch for
Resultis the only error channel — remove a?while adapting and that site needs an explicitmatch.
Using it
The main signature reads fn new() -> Self
The surface worth importing is new; the helpers around it are private to the snippet.
Key statements
pub fn method(mut self, m: &str) -> Self { self.method = Some(m.to_string()); self }
pub fn new() -> Self { Self { method: None, url: None, headers: Vec::new() } }
pub fn url(mut self, u: &str) -> Self { self.url = Some(u.to_string()); self }
Interactive Tools for This Topic
FAQ
- How does the code signal failure?
- As data, not exceptions: `Result` makes the caller handle both arms.
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `new`, `method`, `url` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.