Rust 1.99 (2024 edition) reference · Strings
Rust String::push_str, format! and join Method
Build strings: append with push_str and push, format with format!, and join a list of strings with a separator.
Rust 1.99 (2024 edition)
Syntax
fn push_str(&mut self, s: &str) format!("...", args) fn join(&self, sep: &str) -> String
Parameters
| Parameter | Description |
|---|---|
push_str / push |
Append a &str / a char. |
format! |
Build a String with formatting. |
[..].join(sep) |
Join slices of strings. |
String::with_capacity |
Pre-allocate. |
Examples
fn main() {
let mut s = String::with_capacity(32);
s.push_str("order");
s.push('#');
s += &42.to_string();
println!("{s} ({} bytes)", s.len());
let tags = vec!["rust", "fast", "safe"];
println!("{}", tags.join(", "));
}
Output
order#42 (8 bytes) rust, fast, safe
Run this on your computer — see “Get Started” for setup.
fn main() {
let name = "Ana";
let total = 19.5_f64;
let line = format!("{name:<6}|{total:>8.2}|{:#x}", 255);
println!("{line}");
}
Output
Ana | 19.50|0xff
Run this on your computer — see “Get Started” for setup.
Related
String and &str methods· Common text operations: trim, split, contains, replace, case conversion, starts_with and parse.- Rust Syntax and Printing · tutorial