3

I have seen this question, but still didn't get it, so here's what I know (it might be incorrect):

  • Initializing a variable of type String allocates memory on the heap and stores a pointer to that memory on the stack.
  • Initializing a variable of type &str stores a pointer on the stack, and I'm assuming that pointer points to a str on the heap.

If that's the case - if both String and &str store pointers on the stack pointing to memory locations on the heap - does that mean String and str (not the reference) are the same?

2
  • &str can point anywhere. It can point to .data segment of the executable in case of string literals. It can point to a buffer on the heap owned by some String. It can point to a mmap'd file. str meanwhile is literally just a contiguous region of bytes. Commented Dec 26, 2020 at 12:33
  • @IvanC Thank you for your answer, I didn't know that. Commented Dec 26, 2020 at 13:11

1 Answer 1

9

This article explains quite well, and has some visuals as to how both work : https://blog.thoughtram.io/string-vs-str-in-rust/.

To answer your question, no they are not the same. They can just point to the same thing.

A String is a container which stores text using strs. It owns the data it points to, and can modify it or add/remove from it.

From the article, a str is :

String slices (or str) are what we work with when we either reference a range of UTF-8 text that is “owned” by someone else, or when we create them using string literals.

So str only points to data, and can point to a substring of some data as well. But it doesn't own the data and can't modify it.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer, it is well explained. You said str only points to data and cannot modify it, but I'm new to Rust and have noticed that this compiles just fine let mut name: &str = "Jake Gyllenhall"; name = "Tom Holland";. Could you please explain what is happening here?
This is because of the variable binding, you're changing what the variable points to, but not the underlying data. When you're assigning to name, you're changing the previous pointer with the new pointer. See here play.rust-lang.org/…, I output the address, you can see it changes each time.
Put simply: String is literally Vec<u8>, and &str is literally &[u8].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.