Rust Drop trait

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

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

struct Example  
{  
  a : i32,  
 }  
      impl Drop for Example  
{  
  fn drop(&mut self)  
  {  
    println!("Dropping the instance of Example with data : {}", self.a);  
  }  
}  
      fn main()  
{  
  let a1 = Example{a : 10};  
  let b1 = Example{a: 20};  
  println!("Instances of Example type are created");  
}

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

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函数来删除该值。

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

struct Example  
{  
  a : String,  
}  
impl Drop for Example  
{  
  fn drop(&mut self)  
  {  
    println!("Dropping the instance of Example with data : {}", self.a);  
  }  
}  
fn main()  
{  
  let a1 = Example{a : String::from("Hello")};  
  a1.drop();  
  let b1 = Example{a: String::from("World")};  
  println!("Instances of Example type are created");  
}

执行上面示例代码,得到以下结果 –
《Rust Drop trait》

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

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

 struct Example  
{  
  a : String,  
}  

impl Drop for Example  
{  
  fn drop(&mut self)  
  {  
    println!("Dropping the instance of Example with data : {}", self.a);  
  }  
}  

fn main()  
{  
  let a1 = Example{a : String::from("Hello")};  
  drop(a1);  
  let b1 = Example{a: String::from("World")};  
  println!("Instances of Example type are created");  
}

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

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

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

        原文作者:Rust教程
        原文地址: https://www.yiibai.com/rust/rust-drop-trait.html
        本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
    点赞