橘子味的心
标题:Rust Drop trait

drop trait用于在值超出范围时释放文件或网络连接等资源。
drop trait用于释放Box <T>指向的堆上的空间。
drop trait用于实现drop()方法,该方法对self进行可变引用。

下面来看一个简单的例子:

  1. struct Example
  2. {
  3. a : i32,
  4. }
  5. impl Drop for Example
  6. {
  7. fn drop(&mut self)
  8. {
  9. println!("Dropping the instance of Example with data : {}", self.a);
  10. }
  11. }
  12. fn main()
  13. {
  14. let a1 = Example{a : 10};
  15. let b1 = Example{a: 20};
  16. println!("Instances of Example type are created");
  17. }
  18. Rust

执行上面示例代码,得到以下结果 -

  1. Instances of Example type are created
  2. Dropping the instance of Example with data : 20
  3. Dropping the instance of Example with data : 10
  4. Shell

程序代码说明

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

注意 : 不需要显式调用drop()方法。 因此,可以说当实例超出范围时,Rust会隐式调用drop()方法。

使用std::mem::drop尽早删除值

有时,有必要在范围结束之前删除该值。如果想提前删除该值,那么使用std::mem::drop函数来删除该值。

下面来看一个手动删除值的简单示例:

  1. struct Example
  2. {
  3. a : String,
  4. }
  5. impl Drop for Example
  6. {
  7. fn drop(&mut self)
  8. {
  9. println!("Dropping the instance of Example with data : {}", self.a);
  10. }
  11. }
  12. fn main()
  13. {
  14. let a1 = Example{a : String::from("Hello")};
  15. a1.drop();
  16. let b1 = Example{a: String::from("World")};
  17. println!("Instances of Example type are created");
  18. }
  19. Rust

执行上面示例代码,得到以下结果 -

在上面的例子中,手动调用drop()方法。 Rust编译器抛出一个错误,不允许显式调用drop()方法。不是显式调用drop()方法,而是调用std::mem::drop函数在值超出范围之前删除它。

std::mem::drop函数的语法与Drop trait中定义的drop()函数不同。 std::mem::drop函数包含作为参数传递的值,该值在超出范围之前将被删除。
下面来看一个简单的例子:

  1. struct Example
  2. {
  3. a : String,
  4. }
  5.  
  6. impl Drop for Example
  7. {
  8. fn drop(&mut self)
  9. {
  10. println!("Dropping the instance of Example with data : {}", self.a);
  11. }
  12. }
  13.  
  14. fn main()
  15. {
  16. let a1 = Example{a : String::from("Hello")};
  17. drop(a1);
  18. let b1 = Example{a: String::from("World")};
  19. println!("Instances of Example type are created");
  20. }
  21. Rust

执行上面的示例代码,得到以下结果 -

  1. Dropping the instance of Example with data : Hello
  2. Instances of Example type are created
  3. Dropping the instance of Example with data : World
  4. Shell

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