Impl Trait + lifetime in return position

In this code: rustc-fn:

pub fn elements(&self) -> impl Iterator<Item = Region<'tcx>> + '_ {

Q: Why is the lifetime '_ required?

I searched and found this: Generic parameter capture - Impl trait initiative which doesn't help and in the issue `impl Trait` Lifetime Elision · Issue #43396 · rust-lang/rust · GitHub niko said:

  • Lifetimes can be elided, but if you just write impl Trait it does not capture &self . To capture, you must write impl Trait + '_ .

But I do not understand why need to capture &self.

Are you sure this is copying all the data and not returning any even partial reference to self?

The iterator you use is lazy, so the original object needs to stay alive to provide new results. You could instead use a non-lazy iterator, which would look something like this:

pub fn elements(&self) -> impl Iterator<Item = Region<'tcx>> {
    let v: Vec<_> = self.relation.elements().copied().collect();

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.