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