The very first problem is that I really don't understand what the compiler wants here and what's the problem, as in my opinion, the lifetimes here are perfectly valid and identical, so both traits should treat a reference of the same lifetime, but the compiler says the lifetimes are different and somehow any use of an object require static lifetime, even though a specific lifetime is specified ('a
). Playground.
struct Intersection<'a, T: ?Sized> {
object: &'a T,
value: f32,
}
trait IntersectionsWith<'a, T: ?Sized> {
fn intersections_with(&self, obj: &'a T) -> Vec<Intersection<'a, T>>;
}
struct Ray;
impl<'a, T> IntersectionsWith<'a, T> for Ray {
fn intersections_with(&self, obj: &'a T) -> Vec<Intersection<'a, T>> {
vec![]
}
}
trait ColoredHit<'a, T: ?Sized> {
fn colored_hit(&self, obj: &'a T) -> f32;
}
trait ObjectLike<T> {}
impl<'a, T> ColoredHit<'a, dyn ObjectLike<T>> for Ray
where
Ray: IntersectionsWith<'a, dyn ObjectLike<T>>,
{
fn colored_hit(&self, obj: &'a dyn ObjectLike<T>) -> f32 {
let intersections = self.intersections_with(obj);
0.0f32
}
}
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/main.rs:29:53
|
29 | let intersections = self.intersections_with(obj);
| ^^^
|
note: first, the lifetime cannot outlive the lifetime `'a` as defined here...
--> src/main.rs:24:6
|
24 | impl<'a, T> ColoredHit<'a, dyn ObjectLike<T>> for Ray
| ^^
note: ...so that the declared lifetime parameter bounds are satisfied
--> src/main.rs:29:53
|
29 | let intersections = self.intersections_with(obj);
| ^^^
= note: but, the lifetime must be valid for the static lifetime...
note: ...so that the expression is assignable
--> src/main.rs:29:53
|
29 | let intersections = self.intersections_with(obj);
| ^^^
= note: expected `&(dyn ObjectLike<T> + 'static)`
found `&dyn ObjectLike<T>`
I have already tried specifying more lifetimes, being very explicit about what &self
, and &obj
lifetimes are and that all of them are distinct, tried specifying that the lifetimes are different and one is longer than the other like 'a: 'b
but nothing helped, it just continued complaining, but this time it was that the object doesn't live long enough and it wasn't the 'static
lifetime it complained about but 'a
or the very first used.