问题描述
让线程状态由不可变参数Params
和其余(可变)状态State
组成。
我正在尝试模拟生成一个由参数Params
控制的线程:
use std::thread;
struct Params {
x: i32,}
struct State<'a> {
params: &'a Params,y: i32,}
impl<'a> State<'a> {
fn new(params: &Params) -> State {
State {
params,y: 0,}
}
fn start(&mut self) -> thread::JoinHandle<()> {
let params = self.params.clone();
thread::spawn(move || { params; /* ... */ })
}
}
但这不起作用:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> test.rs:20:34
|
20 | let params = self.params.clone();
| ^^^^^
|
note: first,the lifetime cannot outlive the lifetime `'a` as defined on the impl at 12:6...
--> test.rs:12:6
|
12 | impl<'a> State<'a> {
| ^^
note: ...so that the types are compatible
--> test.rs:20:34
|
20 | let params = self.params.clone();
| ^^^^^
= note: expected `&&Params`
found `&&'a Params`
= note: but,the lifetime must be valid for the static lifetime...
note: ...so that the type `[[email protected]:21:23: 21:42 params:&Params]` will meet its required lifetime bounds
--> test.rs:21:9
|
21 | thread::spawn(move || { params; /* ... */ })
| ^^^^^^^^^^^^^
我理解为什么它不起作用:该线程可以无限期地运行,并且params
可以在终止之前被销毁。显然这是一个错误。
现在说明什么使params
至少与线程一样长的正确方法。换句话说,有助于更正上面的代码。我该怎么办?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)