让我们看看一个简单的例子:
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函数删除该值。
链接:https://www.learnfk.comhttps://www.learnfk.com/rust/rust-drop-trait.html
来源:LearnFk无涯教程网
让我们看一下一个简单的例子来手动删除值:
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实例。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)