我想让闭包包含&mut Vec,但是这些简单的几行代码无法编译。
我知道这可以通过RefCell解决,我只是无法弄清错误。
struct Server<'a> {
data: &'a mut Vec<i32>,
}
fn main() {
let mut data = vec![1, 2, 3];
let mut c = || {
Server{
data: &mut data,
}
};
let server = c();
}
错误消息是:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src/main.rs:36:19
|
36 | data: &mut data,
| ^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime '_ as defined on the body at 34:17...
--> src/main.rs:34:17
|
34 | let mut c = || {
| ^^
note: ...so that closure can access `data`
--> src/main.rs:36:19
|
36 | data: &mut data,
| ^^^^^^^^^
note: but, the lifetime must be valid for the call at 39:18...
--> src/main.rs:39:18
|
39 | let server = c();
| ^^^
note: ...so type `Server<'_>` of expression is valid during the expression
--> src/main.rs:39:18
|
39 | let server = c();
| ^^^
error: aborting due to previous error
更新:
我发现this post回答了这个问题,但是我听不懂它的某些部分:
事实证明,对于短寿命的call_mut调用,返回&'a mut i32是不可行的。我们真正想要的call_mut返回类型是:
impl<'a> FnMut<(usize,)> for Closure<'a> {
extern "rust-call"
fn<'b> call_mut(&'b mut self, (i,): (usize, )) -> &'b mut i32 {
self.inner.get_mut(i).unwrap()
}
}
call_mut
fn必须使用'b
生存期而不是'a
?data: &mut Vec<i32>
更改为data: &Vec<i32>
,该代码将起作用,这使我更加困惑,为什么寿命与mut
有关?