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,
})
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.