When to Use String vs &str

A Lifetime Perspective

Use String for owned, mutable text and &str for borrowed, read-only text slices.

Use String when you need to own, modify, or grow text data; use &str when you only need to read a borrowed slice of text. String allocates memory on the heap and manages its own lifetime, while &str is a reference to data stored elsewhere with a specific lifetime.

fn main() {
    let owned = String::from("hello");
    let borrowed: &str = &owned[..];
    println!("Owned: {owned}, Borrowed: {borrowed}");
}