When I run the following code
struct S;
impl S {
fn data(&self) -> &[u8] {
&[]
}
}
// Works
fn f_1(x: &mut S) -> &[u8] {
S::data(x)
}
// LIFETIME ERROR!
fn f_2(x: &mut S) -> &[u8] {
let closure = move || S::data(x);
closure()
}
I get the error below (link to playground):
Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/lib.rs:16:27
|
16 | let closure = move || S::data(x);
| ^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'_` as defined on the body at 16:19...
--> src/lib.rs:16:19
|
16 | let closure = move || S::data(x);
| ^^^^^^^^^^^^^^^^^^
note: ...so that closure can access `x`
--> src/lib.rs:16:35
|
16 | let closure = move || S::data(x);
| ^
note: but, the lifetime must be valid for the anonymous lifetime defined on the function body at 15:11...
--> src/lib.rs:15:11
|
15 | fn f_2(x: &mut S) -> &[u8] {
| ^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:17:5
|
17 | closure()
| ^^^^^^^^^
Some questions:
- Why would
f_2
give me the lifetime error below? Like,closure
should now be an anonymous struct holdingx
(i.e.,x
got moved intoclosure
) and invoking the closure should return a slice with a lifetime ofS
. - Why would the error disappear if I remove
mut
from&mut S
? Which is, even if my explanation before is wrong, why would adding or removingmut
change the lifetime reasoning here? There does not seem to be any aliasing issue involved. - What can I do to fix this without removing
mut
ormove
?