📅  最后修改于: 2021-01-08 13:59:20             🧑  作者: Mango
让我们看一个简单的例子:
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
注意:我们不需要显式调用drop()方法。因此,可以说当实例超出作用域时,Rust隐式调用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实例。