Rust 专题
您的位置:rust > Rust专题 > Rust Drop trait
Rust Drop trait
作者:--    发布时间:2019-11-20

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");  
}

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

在上面的例子中,手动调用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实例。


网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册