🦀 Rust Beginner

What is the difference between String and &str in Rust?

Answer

String is an owned, heap-allocated, growable UTF-8 string. You can modify it, append to it with push_str(), and it is dropped when it goes out of scope. &str (string slice) is a borrowed reference to a sequence of UTF-8 bytes — it does not own the data and cannot be modified. String literals like "hello" are &'static str (stored in the binary). The relationship: String can be converted to &str cheaply by taking a slice (&my_string), but going from &str to String requires allocation (my_str.to_string() or String::from(my_str)). Functions that only need to read a string should accept &str — it works with both String and string literals, making the API more flexible.