Dropping a mutable reference to a vector and using it afterwards

Hello there,

I am trying to understand why the following code compiles with no errors:

fn consume(w: &mut Vec<i32>) {
	drop(w); // dropping w

fn main() {
	let mut v = vec![10,11];
	consume(&mut v);
	v.push(12); // still using v after drop?

In my understanding, since we are dropping the mutable reference to v, v points to a freed memory location after the call to consume(). Can someone explain to me why this code compiles fine, and the compiler does not complain about a dangling pointer?

Thanks in advance

Dropping a reference does nothing, you can't (safely) drop a type T with only an &mut T

In order to actually drop the Vec you need to call drop with the Vec value.

You can replace the T with a new value via std::mem::replace or similar which would allow you to drop the old value though

1 Like

Why would it? A reference doesn't consume the vector; that's the whole point of references. Passing the vector by value would have destroyed it.

Thanks for pointing that out. My understanding of a reference in Rust was incorrect.