打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
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");  
}Rust

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

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

程序代码说明

  • 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()方法。 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");  
}Rust

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

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

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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
理解Rust中的智能指针
Rust 的 trait 是个啥子?
图解 Rust 所有权与生命周期
​半小时入门Rust,这是一篇Rust代码风暴
初探函数式编程---以Map/Reduce/Filter为例
use关键字在PHP中的几种用法
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服