FAQ - Help and questions

What is the difference between String and &str in Rust?

#strings#basics#ownershippublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

String owns its text on the heap and can grow. &str is a borrowed view of text that lives somewhere else, such as a string literal or part of a String. Take &str in function parameters, because both a String and a literal can be passed as one, and return String when the function creates new text.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
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());
}
text
hello / hello / hello
hello world!!
6 bytes, 5 chars

How to choose#

  • Parameter that only reads text: &str. A call with &my_string works because Rust converts &String to &str automatically.
  • 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() or String::from(...).

Common mistakes#

  • Taking String in 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 &str that points into a local String. The String is freed when the function ends; return the String itself.

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.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet