【问题标题】:Borrow checker "cannot move out of borrowed content" [duplicate]借用检查器“无法移出借用内容” [重复]
【发布时间】:2018-06-19 03:14:05
【问题描述】:

为什么我不能这样做?

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();
}

我收到以下错误,

error[E0507]: cannot move out of borrowed content
   --> src/orderbook.rs:195:9
    |
195 |         self.dispatch_thread.unwrap().join();
    |         ^^^^ cannot move out of borrowed content

【问题讨论】:

  • 感谢格式更正!

标签: rust


【解决方案1】:

这确实是一条不明显的错误消息。看看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()); 同样是非法的;但在这种情况下是有效的,因为我们没有违反该约束。在以&amp;self为接收者的方法中,这是不正确的,这就是为什么在这种情况下它是非法的。

【讨论】:

  • 谢谢!现在更清楚了!
猜你喜欢
  • 2018-04-04
  • 1970-01-01
  • 2015-04-20
  • 2017-10-15
  • 1970-01-01
  • 2019-08-29
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
相关资源
最近更新 更多