error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/lib.rs:14:24
|
14 | iter: self.elements.iter(),
| ^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime defined here...
--> src/lib.rs:12:17
//...
I know why this happens: the elements in self.elements lives as long as &self, so it cannot possibly create an Iter with lifetime a. The easy solution would be to do
This is not even necessarily true, because (AFAICT) your type A<'a, T> is covariant in 'a, so a shorter borrow &'short self of type &'short A<'a, T> can be (often implicitly) converted into &'short A<'short, T>.
In general, the easiest solution to avoid the problem of “borrowing a type for its entire existence” – particularly important in cases where the types involved are not covariant – would be as follows: couple the returned Iter lifetime to &self but make it a different lifetime from the 'a used in the type. E.g.
pub fn iter<'b>(&'b self) -> Iter<'_b T>
or equivalently
pub fn iter(&self) -> Iter<'_, T>
You can also – if you want to be more “precise”– change Iter so it has two lifetime arguments