|
2 | 2 |
|
3 | 3 | ## Description |
4 | 4 |
|
5 | | -Construct an object with calls to a builder helper. |
6 | | - |
| 5 | +Construct an object with calls to a builder helper. |
7 | 6 |
|
8 | 7 | ## Example |
9 | 8 |
|
10 | | -```rust,ignore |
11 | | -struct Foo { |
| 9 | +```rust |
| 10 | +#[derive(Debug, PartialEq)] |
| 11 | +pub struct Foo { |
12 | 12 | // Lots of complicated fields. |
| 13 | + bar: String, |
13 | 14 | } |
14 | 15 |
|
15 | | -struct FooBuilder { |
| 16 | +pub struct FooBuilder { |
16 | 17 | // Probably lots of optional fields. |
17 | | - //.. |
| 18 | + bar: String, |
18 | 19 | } |
19 | 20 |
|
20 | 21 | impl FooBuilder { |
21 | | - fn new( |
22 | | - //.. |
23 | | - ) -> FooBuilder { |
| 22 | + pub fn new(/* ... */) -> FooBuilder { |
24 | 23 | // Set the minimally required fields of Foo. |
| 24 | + FooBuilder { |
| 25 | + bar: String::from("X"), |
| 26 | + } |
25 | 27 | } |
26 | 28 |
|
27 | | - fn named(mut self, name: &str) -> FooBuilder { |
| 29 | + pub fn name(mut self, bar: String) -> FooBuilder { |
28 | 30 | // Set the name on the builder itself, and return the builder by value. |
| 31 | + self.bar = bar; |
| 32 | + self |
29 | 33 | } |
30 | 34 |
|
31 | | - // More methods that take `mut self` and return `FooBuilder` setting up |
32 | | - // various aspects of a Foo. |
33 | | - ... |
34 | | -
|
35 | 35 | // If we can get away with not consuming the Builder here, that is an |
36 | | - // advantage. It means we can use the builder as a template for constructing |
37 | | - // many Foos. |
38 | | - fn finish(&self) -> Foo { |
| 36 | + // advantage. It means we can use the FooBuilder as a template for constructing many Foos. |
| 37 | + pub fn build(self) -> Foo { |
39 | 38 | // Create a Foo from the FooBuilder, applying all settings in FooBuilder to Foo. |
| 39 | + Foo { bar: self.bar } |
40 | 40 | } |
41 | 41 | } |
42 | 42 |
|
43 | | -fn main() { |
44 | | - let f = FooBuilder::new().named("Bar").with_attribute(...).finish(); |
| 43 | +#[test] |
| 44 | +fn builder_test() { |
| 45 | + let foo = Foo { |
| 46 | + bar: String::from("Y"), |
| 47 | + }; |
| 48 | + let foo_from_builder: Foo = FooBuilder::new().name(String::from("Y")).build(); |
| 49 | + assert_eq!(foo, foo_from_builder); |
45 | 50 | } |
46 | | -
|
47 | 51 | ``` |
48 | 52 |
|
49 | 53 |
|
@@ -91,10 +95,10 @@ one can write code like |
91 | 95 | let mut fb = FooBuilder::new(); |
92 | 96 | fb.a(); |
93 | 97 | fb.b(); |
94 | | -let f = fb.finish(); |
| 98 | +let f = fb.build(); |
95 | 99 | ``` |
96 | 100 |
|
97 | | -as well as the `FooBuilder::new().a().b().finish()` style. |
| 101 | +as well as the `FooBuilder::new().a().b().build()` style. |
98 | 102 |
|
99 | 103 | ## See also |
100 | 104 |
|
|
0 commit comments