gpt4 book ai didi

rust - 使用线程时 Rust 中 self 参数的生命周期

转载 作者:行者123 更新时间:2023-11-29 08:15:15 26 4
gpt4 key购买 nike

<分区>

我正在学习 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 中变量的生命周期。无论我用这个函数做什么,我仍然会遇到这种类型的错误。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com