Understanding the differences between String and str — How to Rust
In Rust, String
and str
are two core types that handle string data, but they do so in different ways, catering to different needs in the language's memory safety and management model. Here's a breakdown of their key differences:
String
- Type:
String
is a growable, heap-allocated data structure. This means that it can change size at runtime, and it is stored in the heap memory, which allows it to store an amount of text that is unknown at compile time or that might change over time. - Ownership: Being a heap-allocated value, a
String
owns its contents. This plays into Rust's ownership rules, meaning that when aString
is moved from one variable to another, the original variable is no longer accessible. This prevents memory safety issues like dangling pointers. - Usage: Use
String
when you need to modify or own your string data, such as appending characters or slicing and altering the string at runtime.
str
- Type:
str
, often seen in its borrowed form&str
, is an immutable sequence of UTF-8 characters.str
itself is a slice ([u8]
) and is typically used in its borrowed form,&str
, which is a reference to a string slice. It is often referred to as a "string slice". - Ownership: Since
&str
is a reference, it does not own the data it points to. Instead, it borrows it from some other owner (like aString
or another&str
). This means you can have multiple references to the same string data without copying it, ensuring efficient memory usage and access. - Usage:
&str
is used when you want to access or pass around string data without taking ownership of it. This is common for function parameters that need to read or inspect string data without modifying it.
Key Differences Summarized
- Memory Allocation:
String
is stored on the heap and can be resized, whereasstr
is a fixed-size slice that can live on the stack, in the heap, or in the binary's static memory section (for string literals). - Ownership and Borrowing:
String
follows Rust's ownership rules, while&str
is typically used in a borrowing context. - Mutability:
String
can be modified (e.g., appending, removing, changing characters), butstr
is immutable.
Conversion
It’s common to convert between String
and &str
:
- To get a
&str
from aString
, you can use theas_str()
method or simply borrow theString
with&
. - To create a
String
from a&str
, you can use theto_string()
method or theString::from()
function.
Understanding when to use each and how to convert between them is a fundamental part of effective Rust programming, ensuring that you can manage string data efficiently while adhering to the language’s strict memory safety and ownership models.