Specifying lifetimes of impl traits


I thought that impl Iterator<Item=&u32> +'a was the impl trait equivalent of std::slice::Iter<'a, u32> That is to say both the Iter object and the anonymous trait object that implements Iterator would exist for lifetime 'a.

But this doesn't seem to be the case. I couldn't figure out how to specify a lifetime for an impl trait object in a way that would compile. Sorry for the naive question. The documentation on impl traits is a little sparse at the moment. Impl trait type - The Rust Reference

Thanks in advance.

I don't know what code you tried and found that it didn't work, but try this:

impl Iterator<Item=&'a u32>

Note that this use of 'a on the reference implicitly adds an + 'a like you have on yours.

Sweet! impl Iterator<Item=&'a u32> totally worked!

I don't understand why impl Iterator<Item=&u32> +'a didn't, but I'm still happy.

Thank you!

Well without a lifetime on the reference you are:

  1. Not telling Rust which exact type the iterator returns.
  2. But telling Rust that the iterator might contain references of lifetime 'a.

There's nothing here that says that the references it returns must have that lifetime.
Note that &'a u32 and &'b u32 are different types when 'a ≠ 'b.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.