RustDropTrait

/ / RustDropTrait
  • 当值超出范围时,丢弃特性用于释放文件或网络连接之类的资源。
  • 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函数删除该值。

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

 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实例。

无涯教程网

祝学习愉快! (发现内容有误?请选中要编辑的内容 -> 右键 -> 修改 -> 提交!帮助我们改进教程质量)

精选教程推荐

👇 以下精选教程可能对您有帮助,拓展您的技术视野

结构思考力 · 透过结构看思考 -〔李忠秋〕

手把手带你写一个MiniSpring -〔郭屹〕

云原生架构与GitOps实战 -〔王炜〕

Go 语言项目开发实战 -〔孔令飞〕

爆款文案修炼手册 -〔乐剑峰〕

检索技术核心20讲 -〔陈东〕

性能工程高手课 -〔庄振运〕

高并发系统设计40问 -〔唐扬〕

技术与商业案例解读 -〔徐飞〕

📝 好记忆不如烂笔头,留下您的学习笔记吧!

暂无学习笔记,成为第一个分享的人吧!

您的笔记将帮助成千上万的学习者