Strings
Owned String vs &str
&str is a view into text. String owns growable UTF-8 data.
let slice: &str = "hello";
let owned: String = String::from("hello");
println!("{slice} {owned}");
Append and format
Push text onto a String or build with format!.
let mut s = String::from("hi");
s.push_str(" there");
let msg = format!("{s}!");
println!("{msg}");
Pass string slices to functions
Prefer &str parameters so both String and literals work.
fn shout(text: &str) {
println!("{}", text.to_uppercase());
}
shout("rust");
shout(&owned);
UTF-8 caution
- Indexing by byte can panic on multibyte characters
- Iterate with
.chars()when you need Unicode scalars - Length in bytes and length in chars can differ
- Use the standard library docs when slicing text
Comments
One comment per signed-in account. Comments are saved with this page’s URL.