Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't rust complain when you drop a value that lives on the stack

Tags:

rust

I'm learning about rust references and I am wondering about the drop() function. In this example is &Box<i32> a reference to something on the stack or heap.

let y = 32; // `y` lives on the stack
drop(y); // why doesn't this complain
println!("{}", y); // this also doesn't complain
like image 673
masonCherry Avatar asked Sep 16 '25 22:09

masonCherry


1 Answers

drop is not a special function. All it does is take ownership of the value passed in, which is then destroyed when the function returns. The documentation even says this:

This function is not magic; it is literally defined as

pub fn drop<T>(_x: T) { }

Because _x is moved into the function, it is automatically dropped before the function returns.

What if you have a function that takes an i32?

fn example(_v: i32) { }

When you call this, the i32 value you provide is copied, because i32 implements the Copy trait. This allows you to use the supplied value again later.

All Copy does is make it so that when a move of an implementing value is attempted, a bitwise copy is performed instead, which leaves the source value usable.

It should be clearer now why this doesn't cause a problem. The value in y is copied into the _x argument of drop(). Since it is copied and not moved, y is still usable.

If you change your code so that y holds a value of a type that does not implement Copy, you will see a compile-time error as you expect.

like image 92
cdhowie Avatar answered Sep 19 '25 09:09

cdhowie