Answer#
Both hold UTF-8 text. String is the owner: it allocates, can be changed and grown, and frees its memory when it goes out of scope. &str is a reference to some text owned by someone else: a literal baked into the program, a String, or a piece of either. A &str is cheap to pass around because only a pointer and a length are copied.
fn first_word(text: &str) -> &str {
text.split_whitespace().next().unwrap_or("")
}
fn main() {
let owned: String = String::from("hello world"); // owns its text on the heap, can grow
let literal: &str = "hello world"; // a view of text stored in the program
let part: &str = &owned[0..5]; // a view of part of `owned`
let mut grown = owned.clone();
grown.push_str("!!");
println!("{} / {} / {}", first_word(&owned), first_word(literal), part);
println!("{grown}");
println!("{} bytes, {} chars", "héllo".len(), "héllo".chars().count());
}hello / hello / hello
hello world!!
6 bytes, 5 charsHow to choose#
- Parameter that only reads text:
&str. A call with&my_stringworks because Rust converts&Stringto&strautomatically. - Struct field or return value that must keep the text:
String. - Text that is built or changed (
push_str,format!):String. - To get an owned copy of a
&str:.to_string(),.to_owned()orString::from(...).
Common mistakes#
- Taking
Stringin a parameter when the function only reads it. Callers are then forced to give the text away or clone it. - Indexing text by number, as in
text[2]. That does not compile, because a byte offset may fall in the middle of a character. The last line of the output shows why:"héllo"is 6 bytes but 5 characters. Use.chars(), or slice with byte ranges you know are on character boundaries. - Returning a
&strthat points into a localString. The String is freed when the function ends; return theStringitself.
Related questions#
Is a string literal a String?#
No. "abc" has the type &'static str: a view of text stored in the program that is valid for the whole run.
How do I join strings?#
format!("{a} {b}") creates a new String. a + &b works when a is a String that you are done with. push_str appends in place.