How do I write the lifetimes for references in a type constraint when one of them is a local reference?
You need higher-ranked trait bounds (HRTBs), which are described in the advanced Rust book Rustonomicon and well as on Stack Overflow. They allow a type constraint to say that trait must be implemented not just for references with a particular lifetime but for any lifetime. They use the where for<>
syntax. Here is the function definition that says an implementation of Mul
is needed for any two references to T
:
fn semi_def<'a, T: Matrix>(x: &'a T) -> T
where
for<'b, 'c> &'b T: Mul<&'c T, Output = T>,
{
&(*x).clone().transpose() * x
}
Because one of the references actually has the lifetime 'a
, not a local lifetime, this could be written with a slightly looser constraint:
fn semi_def<'a, T: Matrix>(x: &'a T) -> T
where
for<'b> &'b T: Mul<&'a T, Output = T>,
{
&(*x).clone().transpose() * x
}
This Q&A is based off a question I asked on the Rust users mailing, which I cleaned up and brought over here for future Rustaceans.