3

Trying to wrap my head around the Rust ownership system and how the compiler implements it. Consider the following example:

fn main() {
    let my_vec = vec![1, 2, 3];
    let x = 5;
    let y = 3.7;

    function_that_takes_ownership(my_vec);
}

fn function_that_takes_ownership(Vec<i32> vec) {
    // ...
}

What actually happens to the stack memory occupied by my_vec when function_that_takes_ownership is called?

I guess, before the call the stack should look like this:

+-----------+
|    ...    |
+-----------+
|   my_vec  | // contains size, capacity and a pointer to heap
+-----------+
|     x     |
+-----------+
|     y     | 
+-----------+  <--- stack pointer points to here

What happens when function_that_takes_ownership is called? Is my_vec copy getting pushed to the stack again, while the old location is now considered unused? Or maybe a pointer to my_vec is actually getting pushed?

kreo
  • 2,613
  • 2
  • 19
  • 31

0 Answers0