The following code, which takes advantage of lifetime elision, compiles:
fn g(a: &mut str, closure: impl Fn(&mut str, &str) -> ()) {
let data = vec![];
for d in data.iter() {
closure(a, d);
}
}
However, suppose that I need to specify the lifetime of variables in the closure explicitly (in my case, the callsite is ambiguous unless I do so). If I add lifetimes explicitly, the compiler complains that a
is mutably borrowed in previous iterations of the closure.
fn g<'b, 'd>(a: &'b mut str, closure: impl Fn(&'d mut str, &str) -> ()) {
let data: Vec<&str> = vec![];
'd: for d in data.iter() {
closure(a, d);
}
}
warning: label name `'d` shadows a lifetime name that is already in scope
--> src/lib.rs:3:5
|
1 | fn g<'b, 'd>(a: &'b mut str, closure: impl Fn(&'d mut str, &str) -> ()) {
| -- first declared here
2 | let data: Vec<&str> = vec![];
3 | 'd: for d in data.iter() {
| ^^ lifetime 'd already in scope
error[E0312]: lifetime of reference outlives lifetime of borrowed content...
--> src/lib.rs:4:17
|
4 | closure(a, d);
| ^
|
note: ...the reference is valid for the lifetime 'd as defined on the function body at 1:10...
--> src/lib.rs:1:10
|
1 | fn g<'b, 'd>(a: &'b mut str, closure: impl Fn(&'d mut str, &str) -> ()) {
| ^^
note: ...but the borrowed content is only valid for the lifetime 'b as defined on the function body at 1:6
--> src/lib.rs:1:6
|
1 | fn g<'b, 'd>(a: &'b mut str, closure: impl Fn(&'d mut str, &str) -> ()) {
| ^^
I assume that's because the compiler won't guess that I only intend 'd
to last for each iteration of the loop. I searched for a way to refer to the lifetime, but all I could find was that I have the ability to specify a "lifetime or label" in the Rust reference book, which seems to only be a label for all intents and purposes.
Is there any way to explicitly specify what the lifetime of each loop iteration is, or otherwise to explicitly write out what the compiler has elided in the first example?