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)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

fn push_str(&mut self, s: &str)   format!("...", args)   fn join(&self, sep: &str) -> String

Parameters

ParameterDescription
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

Example 1
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.

format! with width and precision
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.

Was this page helpful?