Rust - Drop Trait

Rust - Drop Trait 首页 / Rust入门教程 / Rust - Drop Trait
  • 当值超出范围时,丢弃特性用于释放文件或网络连接之类的资源。
  • Drop特性用于取消分配Box <T>指向的堆上的空间。
  • drop trait用于实现drop()方法,该方法对自身进行可变引用。

让我们看看一个简单的例子:

 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

用std::mem::drop删除值

有时,有必要在范围结束之前删除该值。如果我们想及早删除该值,则可以使用std ::mem ::drop函数删除该值。

链接:https://www.learnfk.comhttps://www.learnfk.com/rust/rust-drop-trait.html

来源:LearnFk无涯教程网

让我们看一下一个简单的例子来手动删除值:

 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函数在该值超出作用域之前将其删除。

让我们看看一个简单的例子:

 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

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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

持续交付36讲 -〔王潇俊〕

从0开始学微服务 -〔胡忠想〕

数据结构与算法之美 -〔王争〕

代码精进之路 -〔范学雷〕

苏杰的产品创新课 -〔苏杰〕

实用密码学 -〔范学雷〕

恋爱必修课 -〔李一帆〕

数据分析思维课 -〔郭炜〕

React Native 新架构实战课 -〔蒋宏伟〕

好记忆不如烂笔头。留下您的足迹吧 :)