rust 53 lines · 8 steps

The builder pattern in Rust

A RequestBuilder accumulates HTTP request settings through chainable methods before producing a finished Request.

Explained by highlit
1#[derive(Debug, Default)]
2pub struct RequestBuilder {
3 url: String,
4 method: String,
5 headers: Vec<(String, String)>,
6 body: Option<Vec<u8>>,
7 timeout_ms: u64,
8}
9 
10impl RequestBuilder {
11 pub fn new(url: impl Into<String>) -> Self {
12 RequestBuilder {
13 url: url.into(),
14 method: "GET".to_string(),
15 timeout_ms: 30_000,
16 ..Default::default()
17 }
18 }
19 
20 pub fn method(&mut self, method: impl Into<String>) -> &mut Self {
21 self.method = method.into();
22 self
23 }
24 
25 pub fn header(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
26 self.headers.push((key.into(), value.into()));
27 self
28 }
29 
30 pub fn bearer(&mut self, token: &str) -> &mut Self {
31 self.header("Authorization", format!("Bearer {token}"))
32 }
33 
34 pub fn json(&mut self, payload: &[u8]) -> &mut Self {
35 self.body = Some(payload.to_vec());
36 self.header("Content-Type", "application/json")
37 }
38 
39 pub fn timeout_ms(&mut self, ms: u64) -> &mut Self {
40 self.timeout_ms = ms;
41 self
42 }
43 
44 pub fn build(&self) -> Request {
45 Request {
46 url: self.url.clone(),
47 method: self.method.clone(),
48 headers: self.headers.clone(),
49 body: self.body.clone(),
50 timeout_ms: self.timeout_ms,
51 }
52 }
53}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Returning &mut Self from each setter lets callers chain configuration calls fluently.
  2. 2Accepting impl Into<String> makes an API accept both &str and String without forcing conversions on the caller.
  3. 3A dedicated build step separates the mutable, half-finished builder from the finalized, cloned result.

Related explainers

Share this explainer

Here's the card — post it anywhere.

The builder pattern in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code