Here lifetime 'n is defined by caller and search is enforcing that returned references in Vec match those of &self's lifetime (both have 'p)

My line of thinking is that whenever I call search, I shouldn’t be (manually) concerned about 'n since the compiler will yell at me if somehow names is not in scope and dead. And I think this compiling snippet validates (kinda) my thought.

As you can see &names only lives in runner function and we are returning a Vec of references. To come up with those references we have utilized &names but we are not actually returning them:

Q1: So can we essentially say that search “doesn’t care” about the lifetime 'n? even though it uses it to filter stuff?

Which brings me to my non-compiling version of the code. If instead of returning Vec<&'p str>, we return impl Iterator<Item = &'p str> then it seems the lifetime 'n does matter as the compiler is not happy about early death of names in runner function.

I think the issue here is somewhat similar to how closures are desugared - the impl Iterator synthetic struct is capturing that local vec, but it’s dead after the function. It’s true that the vec isn’t needed but the compiler can’t see this across the function call signatures. Maybe this is a bug or a limitation in how lifetimes in scope are deduced.

I’m on mobile and can’t really play with this at the moment but essentially we want the functions to say (I think) that they return impl Iterator<Item = &'p str> + 'static. I’m assuming that doesn’t work as well but maybe sheds a bit more light on what the compiler is thinking? Although maybe that formulation is non-sensical here; we want to say that the impl doesn’t capture anything beyond what &p is, and I don’t know offhand if you can say that.

Interestingly, this formulation works. It does change the bounds such that the IntoIterator returns &'n S, however. So it seems like the &'p str that’s the S in the original code causes 'p to be captured. Maybe.

Returning a Box<Iterator<Item = &'p str> + 'p> in find_kids is also enough to let the rest compile as-is.