Builder Pattern Rust Typed

Implement a typed builder pattern for constructing complex objects with validation.

RustData Integrity

Code

rustsnippet
25 lines
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

  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

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.