Lifetime issue with unused parameter
⚓ Rust 📅 2026-01-03 👤 surdeus 👁️ 2Hello all,
I've a confusing lifetime issue that I hope you can help me with.
pub fn find_items<F>(input: &str, checker: F) -> impl Iterator<Item = usize>
where
F: Fn(usize) -> bool,
{
let range = (0..42);
range.filter(|id| checker(*id))
}
The function above produces this error below, which says a lifetime bound needs to be added for checker for it to be valid for the lifetime of input. This is confusing since even though the function takes input, it never uses it. And I'm unsure if the fix suggested here is even the appropriate one.
error[E0311]: the parameter type `F` may not live long enough
--> day-02-gift-shop/src/lib.rs:39:5
|
34 | pub fn find_items<F>(input: &str, checker: F) -> impl Iterator<Item = usize>
| ---- the parameter type `F` must be valid for the anonymous lifetime defined here...
...
39 | range.filter(|id| checker(*id))
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...so that the type `F` will meet its required lifetime bounds
|
help: consider adding an explicit lifetime bound
|
34 ~ pub fn find_items<'a, F>(input: &'a str, checker: F) -> impl Iterator<Item = usize>
35 | where
36 ~ F: Fn(usize) -> bool + 'a,
|
I think the cause is that the Filter iterator returned by .filter might hold the predicate provided to it, i.e., the closure |id| checker(*id). The closure captures checker by reference because checker is of type Fn and calling an Fn only requires a &self. So the fix is to tell the closure to take checker by value by using .filter(move |id| checker(*id)).
This is either a bug or I'm missing something, which if true I would greatly appreciate if you could help point it out.
3 posts - 3 participants
🏷️ Rust_feed