Rust: difference between &str, &String and String
Comparison table of the three Rust string types: data ownership, memory layout and mutability.
In Rust, three string notions are easy to mix up: &str, &String and String. This memo compares them.
Comparison
| Type | What is it? | Owns the data? | In memory | Mutable? |
|---|---|---|---|---|
&str |
Reference to text | No | Pointer to data (often read-only) | No |
&String |
Reference to a String object |
No (the String owns it) |
Pointer to a String object, which points to the heap |
Indirectly, through the object |
String |
Owned string | Yes | Object (ptr, len, cap) + data on the heap | Yes |
Examples
let s = "qsdf"; // s: &str
let s = String::from("qsdf"); // s: String
let r = &s; // r: &String
Details
&str: a literal such as"qsdf"is already a&str, pointing to static read-only text.String: holds a pointer (ptr), a length (len) and a capacity (cap); the data is allocated on the heap. It is mutable (push_str,clear, etc.) and freed automatically when it goes out of scope (RAII).&String:rdoes not own the data, it points to the objects. A&Stringcan be used where a&stris expected (automatic conversion).