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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With