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");
}
执行上面示例代码,得到以下结果 -
instances of example type are created
dropping the instance of example with data : 20
dropping the instance of example with data : 10
程序代码说明
example
类型上实现了drop trait
,并在drop trait
的实现中定义了drop()
方法。main()
函数中,创建了example
类型的实例,并且在main()
函数的末尾,实例超出了范围。drop()
方法来删除example
类型的实例。 首先,它将删除b1
实例,然后删除a1
实例。注意 : 不需要显式调用
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
函数在值超出范围之前删除它。
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");
}
执行上面的示例代码,得到以下结果 -
dropping the instance of example with data : hello
instances of example type are created
dropping the instance of example with data : world
在上面的示例中,通过在drop(a1)
函数中将a1
实例作为参数传递来销毁a1
实例。