Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do user-defined rust types implement drop?

Do user-defined rust types get an automatic drop implementation for them, if they have a field or variant that might contain an item that needs to be dropped?

Consider a struct as follows:

struct Guard<T> {
  pointer: Box<T>,
  locked: bool
}

Is this struct going to automatically have drop implemented for it? How about if the type was an enum, where only one variant had the box?

enum MaybeDroppable<T> {
    A(Box<T>),
    B
}
like image 469
Waleed Dahshan Avatar asked Oct 24 '25 05:10

Waleed Dahshan


1 Answers

I think your question stems from some confusion between implementing the Drop trait, and variables being dropped when they go out of scope.

When a variable goes out of scope it is dropped (unless it is uninitialized) meaning its destructor is called and its memory can be reused after the destructor has finished. If this variable is of a type that implements the Drop trait then its drop implementation is run first as part of its destructor.

So, the Drop trait (merely) provides a way to run user-defined code when a variable gets dropped. It has no bearing on whether (or when) a variable is dropped.

For a compound variable this process happens recursively (and in a special order) for each field, such that you don't have to do anything in almost all circumstances.

like image 88
hkBst Avatar answered Oct 26 '25 19:10

hkBst



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!