Rust 语言 - Drop & Borrow checker


fn testing(myptr :&mut Box<i32>) {
println!("Fn is called: {}",myptr);
*myptr=Box::new(300);
println!("Inside: {}",myptr);
*myptr=Box::new(0);
println!("Inside: {}",myptr);
drop(myptr);
}
fn main() {
let mut myptr = Box::new(100);
println!("Before Func: {}",myptr);
testing(&mut myptr);
println!("From Main: {}",myptr);
}

输出
Before Func: 100
Fn is called: 100
Inside: 300
Inside: 0
From Main: 0

因为我已经调用了drop函数,我希望这个值不能从主函数访问,但这并没有发生。我不明白为什么。需要帮助了解谁拥有所有权以及为什么drop功能不起作用。

在这种情况下,对drop(myptr)的调用不会丢弃Box<i32>,它只会丢弃引用,这实际上是一个无操作。你不能通过引用删除某些东西,因为它不拥有值。"From Main:"线会显示什么?

如果您希望myptrtesting()丢弃,那么您将不得不获得它的所有权:

fn testing(myptr: Box<i32>) {
// myptr will be destroyed at the end of the scope
}
fn main() {
let myptr = Box::new(100);
testing(myptr);
// attempting to use it afterwards will yield a compiler error
// println!("From Main: {}", myptr);
}

如果你想让testing()"nullify"myptr,使用Option:

fn testing(myptr: &mut Option<Box<i32>>) {
*myptr = None;
}
fn main() {
let mut myptr = Some(Box::new(100));
println!("Before Func: {:?}", myptr); // prints "Some(100)"
testing(&mut myptr);
println!("From Main: {:?}", myptr); // prints "None"
}

最新更新