Rust 铁锈语言-滴水及;借书检查人

Rust 铁锈语言-滴水及;借书检查人,rust,borrow-checker,Rust,Borrow Checker,因为我调用了drop函数,所以我希望即使从主函数也不能访问该值,但这并没有发生。无法理解为什么。需要帮助了解谁拥有所有权以及drop函数不起作用的原因。在此上下文中对drop(myptr)的调用不会删除框它只会删除引用,这实际上是不可操作的。您不能通过引用删除某些内容,因为它不拥有该值。主:“行打印的”是什么 如果您希望testing()删除myptr,那么您必须拥有它: Before Func: 100 Fn is called: 100 Inside: 300 Inside: 0 From

因为我调用了drop函数,所以我希望即使从主函数也不能访问该值,但这并没有发生。无法理解为什么。需要帮助了解谁拥有所有权以及drop函数不起作用的原因。

在此上下文中对
drop(myptr)
的调用不会删除
它只会删除引用,这实际上是不可操作的。您不能通过引用删除某些内容,因为它不拥有该值。主:“行打印的
”是什么

如果您希望
testing()
删除
myptr
,那么您必须拥有它:

Before Func: 100
Fn is called: 100
Inside: 300
Inside: 0
From Main: 0
Before Func: 100
Fn is called: 100
Inside: 300
Inside: 0
From Main: 0
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);
}
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"
}