为什么我不能创建一个封闭的东西,它产生对封闭东西的可变引用?

时间:2019-09-01 18:14:33

标签: rust closures lifetime

我想创建一个闭包,该闭包以对某项的可变引用为基础,然后返回从原始引用创建的可变引用。

我已将代码最小化为此功能(playground):

fn produce_closure<'a>(string: &'a mut String) -> impl FnMut() -> &'a mut String + 'a {
    move || &mut *string
}

当我尝试编译以上代码时,出现此错误:

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
 --> src/lib.rs:2:13
  |
2 |     move || &mut *string
  |             ^^^^^^^^^^^^
  |
note: first, the lifetime cannot outlive the lifetime '_ as defined on the body at 2:5...
 --> src/lib.rs:2:5
  |
2 |     move || &mut *string
  |     ^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
 --> src/lib.rs:2:13
  |
2 |     move || &mut *string
  |             ^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the function body at 1:20...
 --> src/lib.rs:1:20
  |
1 | fn produce_closure<'a>(string: &'a mut String) -> impl FnMut() -> &'a mut String + 'a {
  |                    ^^
note: ...so that reference does not outlive borrowed content
 --> src/lib.rs:2:13
  |
2 |     move || &mut *string
  |             ^^^^^^^^^^^^

为了弄清楚这种闭合是否可行,我尝试手工编写(playground):

struct HandClosure<'a>(&'a mut String);

impl<'a> HandClosure<'a> {
    fn produce(capture: &'a mut String) -> Self {
        Self(capture)
    }

    fn call_mut(&'a mut self) -> &'a mut String {
        self.0
    }

    fn call_once(self) -> &'a mut String {
        self.0
    }
}

该代码可以正常编译。这是编译器错误吗?我想念什么?

0 个答案:

没有答案