#[derive(Debug)]
struct Appellation {
name: String
}
impl Drop for Appellation {
fn drop(&mut self) {
println!("{:?} dropped", self);
}
}
fn complicated_condition() -> bool {
true
}
fn main() {
let p;
{
let mut q = Appellation {
name: "hello".to_string(),
};
if complicated_condition() {
p = q;
}
}
println!("who drop first?");
}
上面那个代码片段中,Appellation
何时drop取决于complicated_condition
的返回值,如果complicated_condition返回true,那么q的所有权即转移到了p上,当q goes out of scope时,p还活着,所以Appellation将在 println后 drop,如果complicated_condition
返回false,则当q goes out of scope时,Appellation就会drop,将在println之前