3 ms·
> in Rust, I can be sure that `Vec`, `String`, `Box`, `Rc`, and `Arc` are all heap allocated and that slices, arrays, `str`, `&T`, and `&mut T` are not. That's
by dan00 9y ago
> in Rust, I can be sure that `Vec`, `String`, `Box`, `Rc`, and `Arc` are all heap allocated and that slices, arrays, `str`, `&T`, and `&mut T` are not.
That's not really true, because you can easily create e.g. a `&str` out of a
`String` or a `&[T]` out of a `Vec<T>`.
- merb 9y agois there a way to force a copy? like String copy to &str (on the stack?)
- kaoD 9y ago`String` copies are always `String`s and will live on the heap. AFAIK there are no stack strings (plain `str` which I guess is what you mean?) IIRC small fixed-size byte arrays (`[N; u8]`) are sometimes allocated on the stack depending on their size, but they are plain bytes and not full-fledged UTF8 strings. You can convert them into `String` but that would heap-allocate them. To expand on this: in Rust copy strinctly means there is a new owner that is tasked with deallocating that data once it goes out of scope. Move is the same but the ownership is transferred (thus the old owner is no longer responsible for deallocating anything) insted of having a new copy and an additional owner. Copy always results in a new object of the same type. & types are always borrowing. You can't copy into a reference since references are just borrowing of data, and owners of references won't deallocate anything (since they assume that, as long as they can hold an &, the data they reference is still alive, which is true because owners can't deallocate anything if there is a borrow in place). EDIT: I was wrong. As sibling comment says, you can convert a stack-allocated fixed-size array slice into `&str` with `str::from_utf8`. Check the last example here: https://doc.rust-lang.org/std/str/fn.from_utf8.html#examples https://doc.rust-lang.org/std/str/fn.from_utf8.html#examples
- deleted 9y ago[deleted]
- kaoD 9y ago> you can easily create e.g. a `&str` out of a `String` or a `&[T]` out of a `Vec<T>`. I think what op means is both `&str` and `&[T]` live on the stack, even if they reference slices of heap-allocated (or static) data.
- dbaupp 9y agoThe String and Vec objects live on the stack in the same way, but they contain pointers to heap data. I think the grandparent was trying to get at the fact that &str etc don't force things onto the heap nor do they keep things on the heap alive.
- saghm 9y agoYep, from looking at all the comments in response in my original comment, it seems like I didn't do a great job explaining what I meant here; the basic idea is that if I'm trying to optimize my program by minimizing heap allocations, I can safely ignore any instances of &str, &[T], etc. and just focus on String, Vec, etc.