typestar

String and &str in Rust

The owned String versus the borrowed &str.

fn main() {
    let mut owned = String::from("type");
    owned.push_str("star");
    owned.push('!');

    let borrowed: &str = &owned;
    let upper = borrowed.to_uppercase();
    let parts: Vec<&str> = "a,b,c".split(',').collect();
    println!("{owned} {upper} {}", parts.len());
}

How it works

  1. String is growable: push_str and push.
  2. &str borrows a view into it.
  3. Methods like to_uppercase and split return new data.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
257
Tokens
88
Three-star pace
95 tpm

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

Type this snippet

Step 3 of 4 in Slices & strings, step 9 of 15 in Ownership & borrowing.

← Previous Next →