Rust 语言 - 丢弃和借用检查器

Rust language - 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 函数,所以我期望即使从 main 函数也不能访问该值,但事实并非如此。无法理解为什么。需要帮助了解谁拥有所有权以及为什么删除功能不起作用。

在此上下文中对 drop(myptr) 的调用不会删除 Box<i32>,它只会删除 reference,这实际上是一个空操作。您不能通过引用删除某些内容,因为它 拥有 值。 "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()“取消”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"
}