Skip to content

Instantly share code, notes, and snippets.

@jgould22
Created August 9, 2022 14:04
Show Gist options
  • Save jgould22/901c247a7656a4e62138a6ee35a478ba to your computer and use it in GitHub Desktop.
Save jgould22/901c247a7656a4e62138a6ee35a478ba to your computer and use it in GitHub Desktop.
Non Consuming Builder Pattern in rust
// Rust Builder Pattern Example that does not comsume the builder
// I used this to make api client library requests
// I stuggled a bit to figure out that I needed the outer b life time
// to satisfy the lifetimes so I am leaving this here as reference
struct Client {}
struct Foo {
x: i32,
y: i32,
z: i32
}
struct FooBuilder<'a> {
c: &'a Client,
x: i32,
y: i32,
z: i32
}
impl<'b> FooBuilder<'b> {
fn new<'a>(c:&'a Client) -> FooBuilder {
FooBuilder {c: c, x: 0, y: 0, z: 0 }
}
fn set_x<'a>(&'a mut self, x: i32) -> &'a mut FooBuilder<'b> {
self.x = x;
self
}
fn set_y<'a>(&'a mut self, y: i32) -> &'a mut FooBuilder<'b> {
self.y = y;
self
}
fn set_z<'a>(&'a mut self, z: i32) -> &'a mut FooBuilder<'b> {
self.z = z;
self
}
// ... lots of setters
fn build(&self) -> Foo {
Foo {x: self.x, y: self.y, z: self.z}
}
}
fn main() {
let client = Client{};
let mut foo_builder = FooBuilder::new(&client);
foo_builder.set_y(2);
let foo = foo_builder.build();
let foo2 = foo_builder.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