Builder pattern without cloning


#1

Hi,

I tried to implement builder pattern. So I wrote simple struct with String field and added append() function implementation that appends string slice to the String field and returns StringBuilder again. Link to the playground: http://is.gd/pd5INg

My question - is there any other way to implement this append function without cloning the object? (only with lifetimes for example).


#2

Just take mut self instead of &mut self in the append method: http://is.gd/Q4eM5F.


#3

You basically have two approaches to choose from. If you choose the non-consuming

    fn append(&mut self, text: &str) -> &mut StringBuilder

you’ll either have to chain all calls into a single statement:

println!("{}", StringBuilder::new("one")
        .append("two")
        .append("three").get_content());

or call the constructor and modifiers separately:

    let mut builder = StringBuilder::new("one");
    builder.append("two").append("three");
    println!("{}", builder.get_content());

#4

Yes, you typically would use something like this:

fn append(mut self, text: &str) -> StringBuilder
{
    self.content.push_str(text);
    self
}

Note that this takes mut self and returns self at the end. This means the method will take full ownership of the object when append is called, and has to give ownership back to the caller at the end.


#5

Thank you guys!