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
Stringis growable:push_strandpush.&strborrows a view into it.- Methods like
to_uppercaseandsplitreturn new data.
Keywords and builtins used here
StringVecfnletmainmutstr
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.
Step 3 of 4 in Slices & strings, step 9 of 15 in Ownership & borrowing.