The builder pattern in Rust
Chained setters for a type with many optional fields, ending in build.
#[derive(Debug)]
struct Test {
lang: String,
seconds: u32,
editor_mode: bool,
}
struct TestBuilder {
lang: String,
seconds: u32,
editor_mode: bool,
}
impl TestBuilder {
fn new(lang: &str) -> Self {
TestBuilder { lang: lang.to_string(), seconds: 60, editor_mode: false }
}
fn seconds(mut self, seconds: u32) -> Self {
self.seconds = seconds;
self
}
fn editor_mode(mut self, on: bool) -> Self {
self.editor_mode = on;
self
}
fn build(self) -> Test {
Test {
lang: self.lang,
seconds: self.seconds,
editor_mode: self.editor_mode,
}
}
}
fn main() {
let test = TestBuilder::new("rust").seconds(300).editor_mode(true).build();
println!("{:?}", test);
println!("{:?}", TestBuilder::new("sql").build());
}
How it works
- Each setter takes
selfand returns it, so calls chain. buildvalidates and produces the final value.- Defaults live in the builder, not at every call site.
Keywords and builtins used here
SelfStringTestTestBuilderboolbuildeditor_modefalsefnimpllangletmainmutnewsecondsselfstrstructu32
The run, in numbers
- Lines
- 42
- Characters to type
- 702
- Tokens
- 202
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 110 seconds.
Step 1 of 2 in API patterns, step 10 of 12 in Modules, tests & macros.