String — owned, heap-allocated, mutable string. &str — borrowed, immutable string slice.
String:
String::from(), .to_string(), or format!().1let mut s = String::from("hello");2s.push_str(" world");3s.insert(5, ',');4s.truncate(5);5println!("{}", s); // "hello"
&str:
1let literal: &str = "hello";2let owned = String::from("hello");3let slice: &str = &owned;4let sub: &str = &owned[0..3]; // "hel"
When to use:
String for owned, mutable string data.&str for read-only views and function parameters.&str in API design for flexibility.Common mistakes:
s[0] — not allowed (UTF-8).&String auto-derefs to &str.