Waleed Dahshan
Waleed Dahshan

Reputation: 240

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
}

Upvotes: 4

Views: 1511

Answers (2)

hkBst
hkBst

Reputation: 3370

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.

Upvotes: 6

Waleed Dahshan
Waleed Dahshan

Reputation: 240

I want to thank the Rust Discord Members for helping me to answer the question. Essentially the relevant information is in https://doc.rust-lang.org/reference/destructors.html.

Normally in Rust, when a user-defined type is dropped, all of its fields are dropped in order, whether or not there is an implementation of drop for that particular user-defined type. This is called "drop glue" code. If there is an implementation of drop, the drop code runs first, and then every field (in the case of a struct) is dropped, in order.

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

would drop the fields in declaration order. Since pointer needs to be dropped, the code for dropping it is run. As for locked, no code needs to be run in order to drop it.

If the user-defined type is an enum, I believe there is a match statement that runs in order to determine which variants to drop.

Upvotes: 1

Related Questions