I want to create a closure which closes upon a mutable reference to something, and then returns mutable references with created from the original one.
I've minimized my code to this function (playground):
fn produce_closure<'a>(string: &'a mut String) -> impl FnMut() -> &'a mut String + 'a {
move || &mut *string
}
When I try to compile the above code, I get this error:
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
| ^^^^^^^^^^^^
In order to figure out if this kind of a closure was possible, I tried writing it by hand (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
}
}
And that code compiles fine. Is this a compiler bug? What am I missing?