首页 文章

借用检查器“不能移出借来的内容”[重复]

提问于
浏览
0

这个问题在这里已有答案:

为什么我不能这样做?

pub fn start_workers(&mut self) {
    // start all the worker threads
    self.dispatch_thread = Some(spawn(||{
        for _i in 1..10 {
            println!("Price = {}", 10);
            thread::sleep(time::Duration::from_secs(1));
        }
    }));
    self.dispatch_thread.unwrap().join();
}

我收到以下错误,

错误[E0507]:无法移出借来的内容

  • src / orderbook.rs:195:9
    |
    195 | . self.dispatch_thread.unwrap()加入();
    | ^^^^无法移出借来的内容

1 回答

  • 3

    这确实是一个非显而易见的错误消息 . 看一下unwrap的方法签名:

    pub fn unwrap(self) -> T
    

    take

    pub fn take(&mut self) -> Option<T>
    

    unwrap 消耗 Option (注意接收器为 self ),这会使 self.dispatch_thread 处于未知状态 . 如果您使用 take ,它将返回到您可能想要的 None 状态 .

    在这种情况下你可能想要 take ;如下图所示:

    use std::thread;
    use std::time;
    
    struct Foo {
        foo: Option<thread::JoinHandle<()>>,
    }
    
    impl Foo {
        fn nope(&mut self) {
            self.foo = Some(thread::spawn(|| {
                for _i in 1..10 {
                    println!("Price = {}", 10);
                    thread::sleep(time::Duration::from_millis(10));
                }
            }));
            self.foo.take().unwrap().join();
        }
    }
    
    fn main() {
        let foo = Some(thread::spawn(|| {
            for _i in 1..10 {
                println!("Price = {}", 10);
                thread::sleep(time::Duration::from_millis(10));
            }
        }));
        foo.unwrap().join();
    
        let mut foo = Foo { foo: None };
        foo.foo = Some(thread::spawn(|| {
            for _i in 1..10 {
                println!("Price = {}", 10);
                thread::sleep(time::Duration::from_millis(10));
            }
        }));
        foo.foo.unwrap().join();
    
        let mut foo = Foo { foo: None };
        foo.nope();
    }
    

    请注意 assert!(foo.foo.is_none()); 同样是非法的;但在这种情况下有效,因为我们没有违反该约束 . 在使用 &self 作为接收器的方法中,这不是真的,这就是为什么在这种情况下它是非法的 .

相关问题