LLI Wiki — My Digital Knowledge Base

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

Memory diagram comparing &str, &String and String

Examples

let s = "qsdf";                  // s: &str
let s = String::from("qsdf");    // s: String
let r = &s;                      // r: &String

Details

Mastodon LLIMastodon SocialFosstodon