【问题标题】:Rust language - Drop & Borrow checkerRust 语言 - 拖放和借用检查器
【发布时间】:2021-02-07 06:33:21
【问题描述】:
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 功能不起作用。

【问题讨论】:

    标签: rust borrow-checker


    【解决方案1】:

    在这种情况下对drop(myptr) 的调用不会删除Box&lt;i32&gt;,它只会删除引用,这实际上是一个空操作。您不能通过引用删除某些内容,因为它不拥有该值。 "From Main:" 行会打印什么?

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

    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"
    }
    

    【讨论】:

      猜你喜欢
      • 2018-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 2022-11-11
      相关资源
      最近更新 更多