Rust进阶(6)-drop、trait清理代码

drop、trait清理代码

概述

Drop trait类似于其它语言中的析构函数,当值离开作用域的时候执行此函数的代码

基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Dog {
name: String,
}

impl Drop for Dog {
fn drop(&mut self) {
println!("Dog {} leave", self.name);
}
}

fn main() {
let a = Dog { name: String::from("wangcai") };
{
let b = Dog { name: String::from("dahuang") };
println!("0 +++++++++++++")
}
println!("1 +++++++++++++")
}

输出结果:
表示作用域执行完,才开始释放

1
2
3
4
0 +++++++++++++
Dog dahuang leave
1 +++++++++++++
Dog wangcai leave

drop提前释放

不允许显式调用drop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct Dog {
name: String,
}

impl Drop for Dog {
fn drop(&mut self) {
println!("Dog {} leave", self.name);
}
}

fn main() {
let a = Dog { name: String::from("wangcai") };
let b = Dog { name: String::from("dahuang") };
//提前释放
//b.drop(); //不允许显式调用`drop`,此操作会报错
drop(b); //正确释放
drop(a);
println!("0 +++++++++++++")
}

参考

[1] Rust 程序设计语言

  • Copyrights © 2017-2023 Jason
  • Visitors: | Views:

谢谢打赏~

微信