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

snippet
#[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,
        })
    }
}