The following codes(playground) has compile error:
trait ToCalc {
type T<'l>;
fn to_calc<'l>(&self, data: Self::T<'l>);
}
trait ForCalc {
fn for_calc<'a>(&self, data: &'a Vec<f32>);
}
impl<'l, T> ForCalc for T
where
T: ToCalc<T<'l> = &'l Vec<f32>>,
{
fn for_calc<'a>(&self, data: &'a Vec<f32>) {
self.to_calc(self, data);
}
}
Error: lifetime may not live long enough
╭─[command_13:1:1]
│
10 │ impl<'l, T> ForCalc for T
· ─┬
· ╰── lifetime `'l` defined here
·
14 │ fn for_calc<'a>(&self, data: &'a Vec<f32>) {
· ─┬
· ╰── lifetime `'a` defined here
15 │ self.to_calc(data);
· ─────────┬────────
· ╰────────── argument requires that `'a` must outlive `'l`
────╯
I am trying to understand the error in this way:
The method for_calc
needs the argument data
: &'a Vec<f32>
, but the method self.to_calc
needs the data
: &'l Vec<f32>
. Only when 'a: 'l
, &'l Vec<f32>
can be a subtype of &'a Vec<f32>
. So if I change the trait bound to for<'l> T: ToCalc<T<'l> = &'l Vec<f32>>,
, the codes can compile.
But if I keep the error codes and assuming it can compile. If I apply it in concrete type:
struct Foo;
impl ToCalc for Foo {
type T<'l> = &'l Vec<f32>;
fn calc<'l>(&self, data: Self::T<'l>) {}
}
Next I call:
let data = vec![1f32, 2., 3.];
let data_ref = &data;
Foo.for_calc(data_ref)
Then, data_ref
is the &'a data
, so 'a
= the lifetime of data_ref
. But, what is the 'l
?