ryochack
4/5/2018 - 6:12 AM

builder.rs

#[derive(Clone, Debug)]
struct AnyOption {
    a: bool,
    b: bool,
}

struct AnyBuilder {
    option: AnyOption,
}

struct Any {
    option: AnyOption,
}

impl AnyBuilder {
    fn new() -> AnyBuilder {
        AnyBuilder {
            option: AnyOption { a: false, b: false },
        }
    }

    fn with_a(&mut self) -> &mut Self {
        self.option.a = true;
        self
    }

    fn with_b(&mut self) -> &mut Self {
        self.option.b = true;
        self
    }

    fn build(&self) -> Any {
        Any {
            option: self.option.clone(),
        }
    }
}

fn main() {
    let any = AnyBuilder::new().build();
    println!("{:?}", any);

    let any = AnyBuilder::new().with_a().build();
    println!("{:?}", any);

    let any = AnyBuilder::new().with_a().with_b().build();
    println!("{:?}", any);
}