I'm in the process of learning Rust and I have this code:
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();
}
}
When I try to run it I get:
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 || {
|
I seem to fail to understand the lifetime of variables in rust when using threads. No matter what I do with this function I'm still getting this type of error.