When declaring the String type, I have a question about how memory is allocated in the stack and heap areas.
I think, the memory allocation image would be below.
let s = String::from("hello world");
(A) (B)
+======================+----- static memory -------+======================+
| ... | | "hello world"(12) |
| | | ... |
+======================+------ stack memory -------+======================+
| s(24) | | s(24) |
| data addr | | data addr |
| length | | length |
| capacity | | capacity |
| ... | | ... |
| | | |
| ... | | |
| "hello world"(12) | | ... |
+======================+------- heap memory -------+======================+
Which scenario is correct?
I understand that literal strings are stored in static area during compile time. However, the Rust documentation states that the String type is equivalent to Vec. The Vec type stores all its elements on the heap, so I'm confused as to whether scenario A is correct.
Stringyou copy the string literal's contents from static memory onto the heap.