Builder pattern without cloning



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:

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


Just take mut self instead of &mut self in the append method:


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")

or call the constructor and modifiers separately:

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


Yes, you typically would use something like this:

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

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.


Thank you guys!