Why are methods used in the Builder pattern?


#1
struct FooInfo<'a> {
    name: &'a str,
    n: i32
}

struct Foo<'a> {
    name: &'a str,
    n: i32
}
impl<'a> Foo<'a> {
    fn new<'b>(info: &'b FooInfo<'a>) -> Foo<'a> {
        Foo {
            name: info.name,
            n: info.n
        }
    }
    fn print(&self) {        
        println!("name: {}, n: {}", self.name, self.n);
    }
}

fn main() {
    let s = String::from("123");
    let info = FooInfo { name: &s, n: 0 };
    let foo = Foo::new(&info);
    drop(info);
    foo.print();
}

Why is not the auxiliary structure usually used?


#2

A “bare” config struct is OK too, but you need to be careful about possibility of adding new fields in the future. It’s simple with the builder pattern.

For a bare struct you need to provide Default impl and have at least one private field to force the default to be used. Otherwise you won’t be able to add new fields without breaking existing code.