#![allow(unused)]fnmain() {
#[derive(Debug, PartialEq)]pubstructFoo {
// Lots of complicated fields.
bar: String,
}
impl Foo {
// This method will help users to discover the builderpubfnbuilder() -> FooBuilder {
FooBuilder::default()
}
}
#[derive(Default)]pubstructFooBuilder {
// Probably lots of optional fields.
bar: String,
}
impl FooBuilder {
pubfnnew(/* ... */) -> FooBuilder {
// Set the minimally required fields of Foo.
FooBuilder {
bar: String::from("X"),
}
}
pubfnname(mutself, bar: String) -> FooBuilder {
// Set the name on the builder itself, and return the builder by value.self.bar = bar;
self
}
// If we can get away with not consuming the Builder here, that is an// advantage. It means we can use the FooBuilder as a template for constructing// many Foos.pubfnbuild(self) -> Foo {
// Create a Foo from the FooBuilder, applying all settings in FooBuilder// to Foo.
Foo { bar: self.bar }
}
}
#[test]fnbuilder_test() {
let foo = Foo {
bar: String::from("Y"),
};
let foo_from_builder: Foo = FooBuilder::new().name(String::from("Y")).build();
assert_eq!(foo, foo_from_builder);
}
}