How to use the chained builder pattern in a loop without creating a compiler error?

Viewed 559

How do you properly use a builder pattern that expects method chaining in a loop? Using an example from log4rs. Notice self isn't a reference in appender.

//builder pattern from log4rs

pub struct ConfigBuilder {
    appenders: Vec<Appender>,
    loggers: Vec<Logger>,
}

impl ConfigBuilder {
    pub fn appender(mut self, appender: Appender) -> ConfigBuilder {
        self.appenders.push(appender);
        self
    }
}

Doing this below results in an error because (I think) cb is getting moved to the memory being returned by .appender().

let cb = ConfigBuilder::new();
for x in ys {
    cb.appender(x);
}

This below appears to work. Is this the only way to do it?

let mut cb = ConfigBuilder::new();
for x in ys {
    cb = cb.appender(x);
}
1 Answers
Related