String — owned, heap-allocated, mutable. &str — borrowed, immutable slice of string data.
String:
String::from(), .to_string(), or .format!().1let mut s = String::from("hello");2s.push_str(" world");3s.push('!');4println!("{}", s); // "hello world!"
&str:
"hello") are &str with static lifetime.1let s: &str = "hello"; // Static slice2let owned = String::from("hello");3let slice: &str = &owned; // Borrowed slice4let part: &str = &owned[0..3]; // Partial slice "hel"
When to use:
String when you need to own and modify the string.&str when you just need to read data (function parameters, slices).&str in function signatures for maximum flexibility.Common mistakes:
String after moving it: let s2 = s1; — s1 is gone.s[0] — strings are UTF-8, use .chars() or .bytes() instead.&s on a String gives &String, which auto-derefs to &str.