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()
函數的末尾,實例超出了範圍。 - 當實例移出作用域時,Rust會隱式調用
drop()
方法來刪除Example
類型的實例。 首先,它將刪除b1
實例,然後刪除a1
實例。
注意 : 不需要顯式調用
drop()
方法。 因此,可以說當實例超出範圍時,Rust會隱式調用drop()
方法。
使用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
函數在值超出範圍之前刪除它。
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
實例。
上一篇:
Rust Deref trait
下一篇:無