- 当值超出范围时,丢弃特性用于释放文件或网络连接之类的资源。
- 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");
}
输出:

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