1

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?

skevula
  • 51
  • 8
  • &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. – Ivan C Dec 26 '20 at 12:33
  • @IvanC Thank you for your answer, I didn't know that. – skevula Dec 26 '20 at 13:11

1 Answers1

6

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.

ShadowMitia
  • 2,411
  • 1
  • 19
  • 24
  • 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? – skevula Dec 26 '20 at 13:10
  • 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 https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=08efc22dac55216e101af3ac6eeed394, I output the address, you can see it changes each time. – ShadowMitia Dec 26 '20 at 13:54
  • 3
    Put simply: `String` [is literally `Vec`](https://doc.rust-lang.org/1.48.0/src/alloc/string.rs.html#279-281), and `&str` [is literally `&[u8]`](https://doc.rust-lang.org/1.48.0/src/core/str/converts.rs.html#161-165). – Coder-256 Dec 27 '20 at 00:32