It is not true that a Vec
(the struct containing pointer, length and capacity) is always stored on the stack. You can move any type (excluding self-referential ones, which can't be moved) from the stack to the heap, by putting it in a Box
, Vec
or other heap-using smart pointer. Just consider a straightforward type like i64
: it might be stored on the stack (or in a register if the compiler so chooses), but if you write vec![7i64]
, you have an i64
stored on the heap and the only thing left on the stack is the Vec
itself (a pointer plus length and capacity).
With this analogy, it's not hard to see that the same applies for String
: it can be on the stack, but you can put it on the heap by creating a Vec<String>
. Therefore, if you have a Vec<String>
with length 100, there are 101 independent heap allocations: one owned by the Vec
and one owned by each of the String
s.
See also