Reputation: 1225
I am starting to learn Rust, and it's the first time I've ever worked in a language where you have to think about memory allocation (I've never used C).
As an exercise, I decided to see how I could create a new vector that includes some elements from another vector in addition to some new elements. My goal is to create a vector that maintains pointers to the data in the other vector rather than copying or cloning that data, so that new memory is only allocated for the additional elements. Is that what's happening in the code below, and/or is there a better way to do what I'm trying to do?
fn main() {
let v = vec![vec![1], vec![2], vec![3]];
let v0 = &v[0];
let v1 = &v[1];
let v2 = &vec![4];
let v3 = vec![v0, v1, v2];
}
I used nested vectors because to me, this issue is more pertinent when you're working with data on the heap than on the stack, and vectors are allocated on the heap while integers are on the stack, but keep in mind that I'm a complete novice to this whole domain, so feel free to let me know if what I'm saying and doing makes no sense at all 🙂.
Upvotes: 1
Views: 1135
Reputation: 76683
My goal is to create a vector that maintains pointers to the data in the other vector rather than copying or cloning that data, so that new memory is only allocated for the additional elements. Is that what's happening in the code below[?]
Yes, v3
contains references to the existing vectors that were in v
. It doesn't create new ones or anything.
this issue is more pertinent when you're working with data on the heap than on the stack, and vectors are allocated on the heap while integers are on the stack
This remark is not really true, although using non-Copy types does avoid fooling yourself when you're working on problems like this. Whether a value is on the stack, on the heap, or not on either is for Rust to decide; vec![vec![1]]
vs. vec![1]
would have the value inside the outermost vec just as much on the heap, if we were to guess what Rust would do.
Upvotes: 1