借用检查器和闭包

  • 本文关键字:闭包 rust
  • 更新时间 :
  • 英文 :


所以,我有以下问题。我有一个结构实现,这个结构的一个方法消耗了结构的实例,这对我来说是可以的,因为它实际上是我想在程序中对这个实例(my_struct)做的最后一件事,但它完全不适合借用检查器:

use std::thread;
struct MyStruct {
some_field: Vec<String>
}
impl MyStruct {
fn new() -> Self {
MyStruct {
some_field: vec!("str".to_string())
}
}

fn do_something_with_self_in_thread(&'static mut self) {
thread::spawn(move || self.some_field = vec!("another_str".to_string()));
}
}
fn main() {
let my_struct: &'static mut MyStruct = &mut MyStruct::new();
my_struct.do_something_with_self_in_thread()
// Some blocking call will follow
}

错误:

error[E0716]: temporary value dropped while borrowed
--> src/main.rs:20:49
|
20 |     let my_struct: &'static mut MyStruct = &mut MyStruct::new();
|                    ---------------------        ^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
|                    |
|                    type annotation requires that borrow lasts for `'static`
21 |     my_struct.do_something_with_self_in_thread()
22 | }
| - temporary value is freed at the end of this statement
For more information about this error, try `rustc --explain E0716`.

我试着玩生命周期,但没有结果。

我如何让自己摆脱这种情况?

操场上联系

当我们说方法消费实例,那么它应该取self,而不是定义中的可变借用&mut self。例如

impl MyStruct {
...

fn do_something_with_self_in_thread(self) {
...
}
}

正如评论者已经说过的,你的第二个问题是生命周期。如果引用位于单独的线程中,编译器无法推断它们没有比资源所有者活得长。因此,为此目的,thread::spawn方法具有要求闭包为'static的特征边界,这意味着它捕获的变量可以存活多久就活多久。有效的例子是拥有的类型T,而不是引用&T&mut T,除非它们是&'static T类型。在你的代码中,情况并非如此,因为你在main中实例化了一个结构体(尽管错误地注释为具有'static生命周期),然后试图在闭包中移动一个可变的借用字段。

最新更新