Skip to content

Instantly share code, notes, and snippets.

@shiver
Created May 24, 2017 00:55
Show Gist options
  • Save shiver/7db858f7d82dff10b6aab92bcf3969aa to your computer and use it in GitHub Desktop.
Save shiver/7db858f7d82dff10b6aab92bcf3969aa to your computer and use it in GitHub Desktop.
Rust Builder Pattern
#[derive(Debug)]
struct Builder<'a> {
args: Vec<&'a str>
}
impl<'a> Builder<'a> {
fn new() -> Builder<'a> {
Builder {
args: Vec::new()
}
}
// Builders must consume a mutable self (not a reference) in order to live
// long enough to accept changes from oneliners.
// eg:
// Builder::new().cfg("..").cfg("..");
fn cfg(mut self, value: &'a str) -> Builder<'a> {
self.args.push(&value);
self
}
// This would fail:
// let a = Builder::new().cfg_ref("test").cfg_ref("it");
// | -------------- ^ temporary value dropped here while still borrowed
// | |
// | temporary value created here
// ...
// | }
// | - temporary value needs to live until here
//
fn cfg_ref(&mut self, value: &'a str) -> &mut Builder<'a> {
self.args.push(&value);
self
}
}
fn main() {
let a = Builder::new().cfg("test").cfg("it");
let a = a.cfg("again").cfg("and").cfg("again");
println!("{:#?}", &a);
let mut b = Builder::new();
b.cfg_ref("test");
println!("{:#?}", &b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment