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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With