Function that takes a mutable reference and allocates new memory

Hi,

I would like to ask something.
In the following code the function takes a mutable reference to the vector and in its body allocates new memory for the vector.
My question is when the deallocation (call of drop) for the original vector vec![1, 2, 3, 4] will happen?
The drop shouldn't be called at the end of the function because the functions does not take ownership of the vector.

fn take_vector_mut(list: &mut Vec<i32>) {
    let other = vec![5, 6, 7, 8];
    *list = other;
}

fn main() {
    let mut list_of_numbers = vec![1, 2, 3, 4];
    
    take_vector_mut(&mut list_of_numbers);
    
    println!("{:?}", list_of_numbers);
    
}

The most logical answer that comes to my mind is that deallocation happens in this line:

*list = other;

If this is the case, deallocation of owened memory does not only happen at the end of a function "}", doesn't it?

Thanks a lot!

Yes, assignment drop the value at the assigned place first.

https://doc.rust-lang.org/stable/reference/expressions/operator-expr.html#assignment-expressions

1 Like

No, that's definitely not the only case when a value can be dropped. For example, you can explicitly mention the name of a variable in the middle of a function in order to drop it.

1 Like

How can I do it? Can you please give an example?

You literally just write the name of the variable. Like this: the_variable; – that counts as a use by-value, so it is dropped.

It is moved to nowhere, so it is dropped. Weird but good to know. Thanks a lot!

This is one of the strange things that has to be learned when learning Rust. There is also generic drop routine which does the same thing - drop does nothing with it's argument, the effect is the argument is dropped. The documentation claims "This function is not magic". Some might disagree.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.