Why does Rust have String
and str
? What are the differences between String
and str
? When does one use String
Here is a quick and easy explanation.
String
- A growable, ownable heap-allocated data structure. It can be coerced to a &str
.
str
- is (now, as Rust evolves) mutable, fixed-length string that lives on the heap or in the binary. You can only interact with str
as a borrowed type via a string slice view, such as &str
.
Usage considerations:
Prefer String
if you want to own or mutate a string - such as passing the string to another thread, etc.
Prefer &str
if you want to have a read-only view of a string.