为什么这个生锈的FnMut封闭代码存在生命周期错误?

问题描述 投票:0回答:1

我想让闭包包含&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();
}

Rust playground link

错误消息是:

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()
    }
}
  1. 为什么call_mut fn必须使用'b生存期而不是'a
  2. [我发现如果将data: &mut Vec<i32>更改为data: &Vec<i32>,该代码将起作用,这使我更加困惑,为什么寿命与mut有关?
rust
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.