Builder Pattern With Consuming Methods

Build complex values step by step with consuming methods that return Self, so an incomplete configuration cannot be constructed accidentally.

RustConfig Management

Code

rustsnippet
45 lines
#[derive(Debug)]
struct Request {
    url: String,
    method: String,
    timeout_ms: u64,
    retries: u8,
}

#[derive(Default)]
struct RequestBuilder {
    url: Option<String>,
    method: String,
    timeout_ms: u64,
    retries: u8,
}

impl RequestBuilder {
    fn new() -> Self {
        RequestBuilder {
            method: String::from("GET"),
            timeout_ms: 5000,
            ..Default::default()
        }
    }

    fn url(mut self, url: &str) -> Self {
        self.url = Some(url.to_string());
        self
    }

    fn retries(mut self, retries: u8) -> Self {
        self.retries = retries;
        self
    }

    fn build(self) -> Result<Request, &'static str> {
        let url = self.url.ok_or("url is required")?;
        Ok(Request {
            url,
            method: self.method,
            timeout_ms: self.timeout_ms,
            retries: self.retries,
        })
    }
}

Inside the snippet

Builder Pattern With Consuming Methods comes down to the functions new, url, retries and build.

Errors ride back inside Result, forcing an explicit decision at every call site.

Watch out for

  • Error handling is typed — each Result must be matched or forwarded with ?.

Putting it to use

The primary signature is fn new() -> Self

new is what another module would consume; nothing else here is load-bearing for callers.

Core lines

fn build(self) -> Result<Request, &'static str> {
let url = self.url.ok_or("url is required")?;
Ok(Request {
url,
method: self.method,
timeout_ms: self.timeout_ms,
retries: self.retries,
})
}
fn retries(mut self, retries: u8) -> Self {
self.retries = retries;
self
}
fn url(mut self, url: &str) -> Self {
self.url = Some(url.to_string());
self
}

Interactive Tools for This Topic

FAQ

How do errors reach the caller?
Each fallible operation returns `Result`; nothing is silently discarded.
What has to be installed first?
Nothing — the runtime itself provides everything the code touches. The file defines `new`, `url`, `retries` at load time.