Heya, I'm trying to implement a function that returns an iterator over mutable references of Thing
s, where subsequent Thing
s may be returned based on mutated state of previously returned Thing
s.
Code probably expresses this better than English (playground):
struct Thing {
related_things_processed: bool,
}
struct Things(Vec<Thing>);
// Trying to implement this
fn iterate(things: &mut Things) -> impl Iterator<Item = &mut Thing> + '_ {
std::iter::repeat_with(|| {
things
.0
.iter_mut()
.filter(|item| item.related_things_processed)
// based on things[0] changing state, things[1] may be returned in the next iteration
})
.flatten()
}
fn main() {
iterate(&mut Things(vec![
Thing {
related_things_processed: true,
},
Thing {
// this may be set to true between iterations of things
related_things_processed: false,
},
]));
}
The error message:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/main.rs:9:9
|
9 | / things
10 | | .0
| |______________^
|
note: first, the lifetime cannot outlive the lifetime `'_` as defined on the body at 8:28...
--> src/main.rs:8:28
|
8 | std::iter::repeat_with(|| {
| ^^
note: ...so that closure can access `things`
--> src/main.rs:9:9
|
9 | / things
10 | | .0
| |______________^
note: but, the lifetime must be valid for the anonymous lifetime #1 defined on the function body at 7:1...
--> src/main.rs:7:1
|
7 | fn iterate(things: &mut Things) -> impl Iterator<Item = &mut Thing> + '_ {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that return value is valid for the call
--> src/main.rs:7:36
|
7 | fn iterate(things: &mut Things) -> impl Iterator<Item = &mut Thing> + '_ {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
As I understand it, the problem is the lifetime of the inner iterator value is different from closure invocations, and I haven't managed to convince Rust it's okay. I've tried implementing Iterator
on a struct, but pretty much get the same error.