typestar

Taking &str, returning String in Rust

The API convention: borrow the cheapest thing that works, own what you return.

fn shout(text: &str) -> String {
    text.to_uppercase()
}

fn initials(name: &str) -> String {
    name.split_whitespace()
        .filter_map(|part| part.chars().next())
        .collect()
}

fn main() {
    let owned = String::from("ada lovelace");
    println!("{}", shout("literal"));
    println!("{}", shout(&owned));
    println!("{}", shout(owned.as_str()));
    println!("{}", initials(&owned));
}

How it works

  1. &str accepts both literals and String by deref.
  2. Return String when the function creates new text.
  3. as_str and & bridge the two directions.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
363
Tokens
128
Three-star pace
95 tpm

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

Type this snippet

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

← Previous Next →