Say I want to do lots of small additions to a string in a row, what's the best way to do this? Is there a data type that's best for this?
            Asked
            
        
        
            Active
            
        
            Viewed 1.2k times
        
    26
            
            
        - 
                    It is not too clear what you are asking for. A buffer can be used in many ways. Maybe a parallel with languages having Interned Strings such as Java or C# since those introduced the `StringBuffer` idea would make it clearer. – Matthieu M. Dec 09 '14 at 13:02
2 Answers
41
            Use the String native type, it's designed to be mutable and grow easily.
let mut s = String::new();
s.push_str("GET / HTTP/1.0\r\n");
s.push_str("User-Agent: foobar\r\n"); // Etc etc
 
    
    
        Chris Morgan
        
- 86,207
- 24
- 208
- 215
 
    
    
        Kevin Burke
        
- 61,194
- 76
- 188
- 305
5
            
            
        Say I want to do lots of small additions to a string in a row [...]
If "additions" are not &str you can use the target String as a Writer to push string representations of other data types:
fn main() {
    let mut target_string = String::new();
    use std::fmt::Write;
    write!(target_string, "an integer: {}\n", 42).unwrap();
    writeln!(target_string, "a boolean: {}", true).unwrap();
    assert_eq!("an integer: 42\na boolean: true\n", target_string);
}
The Write trait is required by the macro write!.
Anything which implements write can be written to with the macro write!.
To use Write methods, it must first be brought into scope.
The Write trait is brought into scope with use std::fmt::Write;.
Documentation:
- write!(..): https://doc.rust-lang.org/core/macro.write.html
- writeln!(..): https://doc.rust-lang.org/core/macro.writeln.html
The Resource used to write this answer: Rust String concatenation
 
    
    
        nuiun
        
- 764
- 8
- 19