【发布时间】:2019-08-25 08:13:31
【问题描述】:
我正在学习 Rust,我有这个代码:
use std::sync::{Arc, Mutex};
use std::thread::spawn;
pub struct MyText {
my_text: Mutex<Vec<String>>,
}
pub trait MyTextOptions {
fn add(&self, t: String);
}
impl MyTextOptions for MyText {
fn add(&self, text: String) {
let int_text = Arc::new(self);
let put_into_my_text = spawn(move || {
let mut text_feed = int_text.my_text.lock().unwrap();
text_feed.push(text)
});
put_into_my_text.join();
}
}
当我尝试运行它时,我得到:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src\buffer.rs:37:33
|
37 | let int_text = Arc::new(self);
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 36:5...
--> src\buffer.rs:36:5
|
36 | / fn add(&self, text: String) {
37 | | let int_text = Arc::new(self);
38 | | let put_into_my_text = spawn(move || {
39 | | let mut text_feed = int_text.my_text.lock().unwrap();
... |
42 | | put_into_my_text.join();
43 | | }
| |_____^
= note: ...so that the expression is assignable:
expected &buffer::MyText
found &buffer::MyText
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the type `[closure@src\buffer.rs:38:38: 41:10 int_text:std::sync::Arc<&buffer::MyText>, text:std::string::String]` will meet its required lifetime bounds
--> src\buffer.rs:38:32
|
38 | let put_into_my_text = spawn(move || {
|
在使用线程时,我似乎无法理解 rust 变量的生命周期。不管我用这个函数做什么,我仍然会收到这种类型的错误。
【问题讨论】:
-
基本上,您在该功能期间借用
self。线程可以比该函数更长寿。
标签: rust