typestar

Building strings in Rust

Growing a String, joining pieces, and the cheap ways to slice text.

fn main() {
    let mut report = String::new();
    report.push_str("tours: ");
    report.push_str(&11.to_string());
    report.push('\n');

    let parts = vec!["basics", "errors", "traits"];
    println!("{}", parts.join(" > "));
    println!("{}", "-".repeat(20));

    let line = "  lang = rust  ";
    if let Some((key, value)) = line.trim().split_once(" = ") {
        println!("{key}:{value}");
    }
    print!("{report}");
}

How it works

  1. push_str appends without allocating a new String.
  2. join puts a separator between the parts.
  3. trim, split_once and starts_with borrow rather than copy.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
382
Tokens
139
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 93 seconds.

Type this snippet

Step 3 of 3 in Text, step 29 of 39 in Language basics.

← Previous Next →

Building strings in other languages