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.
Code
#[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
Resultmust 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.