`String` vs `&str`
String is an owned, growable UTF-8 buffer. &str is a borrowed slice of UTF-8. Functions that only read text should take &str; functions that must keep text should take String.
Detailed Explanation
A String is a Vec<u8> that the type system promises is valid UTF-8. It owns its buffer: it can grow (push_str), it can mutate in place when the borrow checker allows, and it frees the buffer on drop. A &str is a fat pointer — address and length — into some UTF-8 bytes you do not own. Those bytes may live in a String, in a binary's static data ("hello"), or in a slice of another &str.
This is the same owned-versus-borrowed split as Vec<T> versus &[T], with one extra rule: both are UTF-8. You cannot index a String with an integer and get a char, because the integer would be a byte index and a char may be several bytes. s[0] does not compile. s.chars().next(), s.get(0..1), or a byte index you already know is a char boundary (s.is_char_boundary) are the tools.
APIs take &str when they read. fn greet(name: &str) accepts String, &String, and "ada" through deref coercion: String implements Deref<Target = str>, so &String becomes &str. APIs take String when they store. fn set_name(&mut self, name: String) makes the caller give you ownership. Taking String when you only read forces a clone at every call site that had a literal or a borrow.
&'static str is a string that lives for the whole program, usually a literal. It is not a String. "ada".to_string() or String::from("ada") allocates. to_owned() on a &str does the same. Avoid those in a loop that already has a String you could push_str into.
OsString and PathBuf are the siblings for platform paths that are not guaranteed UTF-8. CString is the sibling for FFI. Do not store paths in String if you need to round-trip a Windows path that is not valid UTF-8.
When you take &str: reading, comparing, parsing. When you take String: storing, returning a new buffer you created. When you take impl AsRef<str>: you want both and you will only call .as_ref().
Code Examples
fn greet(name: &str) -> String {
let mut out = String::from("hello ");
out.push_str(name);
out
}
fn main() {
let owned = String::from("ada");
println!("{}", greet(&owned)); // prints: hello ada
println!("{}", greet("grace")); // prints: hello grace
println!("{}", "🦀".chars().count()); // prints: 1
println!("{}", "🦀".len()); // prints: 4 — bytes, not chars
}Common Gotchas
No `s[i]` for characters
Byte indexing that is not a char boundary would panic even if it compiled. Iterate `chars` or `char_indices`.
Taking `String` when you read forces clones
A call site with a literal has to allocate. Take `&str`.
`len()` counts bytes
`"é".len()` is 2. `chars().count()` is 1. Graphemes need a crate such as `unicode-segmentation`.
`&String` coerces to `&str`
You rarely need a function that takes `&String`. That type rejects literals.