Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to implement a string buffer in Rust?

Tags:

rust

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?

like image 689
Kevin Burke Avatar asked Dec 09 '14 06:12

Kevin Burke


2 Answers

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

like image 64
nuiun Avatar answered Nov 15 '22 03:11

nuiun


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
like image 21
Kevin Burke Avatar answered Nov 15 '22 03:11

Kevin Burke