3 ms·
> Heap allocated vs. stack/statically allocated. `str` is very rarely stack allocated, and often points into a heap-allocated `String`. Further, there's an opt
by Rusky 9y ago
> Heap allocated vs. stack/statically allocated.
`str` is very rarely stack allocated, and often points into a heap-allocated `String`. Further, there's an optimization on the table that will let `String`s point to static allocations.
The distinction is rather owned vs borrowed. A `String` is in charge of the memory it uses, so it can grow it by reallocation, free it when it goes out of scope, etc. A `str` is not in charge of the memory it uses- it's only a pointer into some memory that something else owns, whether that's a static allocation or a `String` or some other data structure.
- neurotrace 9y agoAhhh, that makes a lot of sense. Thanks for the correction.
- eeereerews 9y agoA `str` is just an unsized blob of UTF-8 data. It's `&str` that is the (fat) pointer.
- Rusky 9y agoYou're right; I kind of left that out since it's not (currently) possible to have a bare `str` anyway and there are more ways to work with one than just `&str` (`Cow<str>`, `Box<str>`, `Rc<str>`, etc).