在Rust中,每一个变量内存被释放时,都会调用他自己的析构函数(Drop trait中的drop方法)。一般情况下,我们不需要也没必要自己实现Drop trait, 编译器会给我们帮忙实现一个默认的。
但如果你定义的结构体包含递归的数据结构,那就要小心了,比如下面的
struct A {
children: Option<Box>
}fn main() {
let mut list = A { children: None };for _ in 0..1_000_000 {
list = A { children: Some(Box::new(list)) };
}println!("for complete, list is going to drop");drop(list);println!("program complete");
}
运行后,结果为(栈溢出了)
Finished dev [unoptimized + debuginfo] target(s) in 0.85s
Running `target\debug\rtest.exe`