作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
<分区>
我正在学习 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 中变量的生命周期。无论我用这个函数做什么,我仍然会遇到这种类型的错误。
我是一名优秀的程序员,十分优秀!