Skip to content

Instantly share code, notes, and snippets.

@4e1e0603
Last active November 19, 2016 17:57
Show Gist options
  • Save 4e1e0603/ed15c6b11324dfa43b0234bf05fc5e33 to your computer and use it in GitHub Desktop.
Save 4e1e0603/ed15c6b11324dfa43b0234bf05fc5e33 to your computer and use it in GitHub Desktop.
Rust Builder Pattern Example
// Rust Builder Pattern Example
struct Foo {
x: i32,
y: i32,
z: i32
}
struct FooBuilder {
x: i32,
y: i32,
z: i32
}
impl FooBuilder {
fn new() -> FooBuilder {
FooBuilder { x: 0, y: 0, z: 0 }
}
fn set_x<'a>(&'a mut self, x: i32) -> &'a mut FooBuilder {
self.x = x;
self
}
fn set_y<'a>(&'a mut self, y: i32) -> &'a mut FooBuilder {
self.y = y;
self
}
fn set_z<'a>(&'a mut self, z: i32) -> &'a mut FooBuilder {
self.z = z;
self
}
// ... lots of setters
fn build(&self) -> Foo {
Foo {x: self.x, y: self.y, z: self.z}
}
}
fn main() {
let foo = FooBuilder::new().set_x(1).set_y(2).set_z(3).build();
println!("x: {}, y: {}, z: {}", foo.x, foo.y, foo.z);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment