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
&straccepts both literals andStringby deref.- Return
Stringwhen the function creates new text. as_strand&bridge the two directions.
Keywords and builtins used here
Stringfninitialsletmainshoutstr
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.
Step 4 of 4 in Slices & strings, step 10 of 15 in Ownership & borrowing.