Drop trait

2025年3月17日 | 阅读 3 分钟
  • Drop trait 用于在值超出作用域时释放资源,例如文件或网络连接。
  • Drop trait 用于释放 Box<T> 指向的堆上的空间。
  • drop trait 用于实现 drop() 方法,该方法接受对 self 的可变引用。

让我们看一个简单的例子

输出

Instances of Example type are created
Dropping the instance of Example with data : 20
Dropping the instance of Example with data : 10

程序说明

  • 我们在类型 Example 上实现了 Drop trait,并在 Drop trait 的实现中定义了 drop() 方法。
  • 在 main() 函数中,我们创建了 Example 类型的实例,并在 main() 函数的末尾,实例超出了作用域。
  • 当实例移出作用域时,Rust 会隐式调用 drop() 方法来释放 Example 类型的实例。首先,它将释放 b1 实例,然后是 a1 实例。

注意:我们不需要显式调用 drop() 方法。因此,我们可以说 Rust 在我们的实例超出作用域时隐式调用 drop() 方法。

使用 std::mem::drop 尽早释放值

有时,需要在作用域结束之前释放值。如果我们想尽早释放值,那么我们使用 std::mem::drop 函数来释放该值。

让我们看一个手动释放值的简单例子

输出

Rust Drop Trait

在上面的例子中,我们手动调用 drop() 方法。Rust 编译器抛出一个错误,即我们不允许显式调用 drop() 方法。我们没有显式调用 drop() 方法,而是调用 std::mem::drop 函数来释放该值,然后该值超出作用域。

  • std::mem::drop 函数的语法与 Drop trait 中定义的 drop() 函数不同。std::mem::drop 函数包含作为参数传递的值,该值将在其超出作用域之前被释放。

让我们看一个简单的例子

输出

Dropping the instance of Example with data : Hello
Instances of Example type are created
Dropping the instance of Example with data : World

在上面的例子中,a1 实例通过将 a1 实例作为参数传递给 drop(a1) 函数而被销毁。


下一个主题Rust Rc(T)