String — owned, heap-allocated, mutable string. &str — borrowed, immutable string slice.
String:
String::from(), .to_string(), format!().1let mut s = String::from("hello");2s.push_str(" world");3s.push('!');4println!("{}", s); // "hello world!"
&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 data.&str for read-only views.&str in APIs.Common mistakes:
s[0] — not allowed.&String auto-derefs to &str.