How does the implementation of this Rust trait work in layman terms?

57 views Asked by At

I wanted to define a trait for a generic type such that its Add operation between two referenced values produces a value of the same type.

The solution that works is as follows:

trait MyTrait<T>: Add<Output = T> + Sized + Clone {}

impl<'a, T: 'a> MyTrait<T> for &'a T where &'a T: Add<Output = T>{}

impl MyTrait<MyStruct> for MyStruct {}

fn some_op<T>(a: &T, b: &T, c: &T) -> T
where
    for<'a> &'a T: MyTrait<T>,
{
    &(a + b) + c
}
// References to MyStruct can be used as inputs to `some_op`

What is the second line of this code doing? It seems to reimplementing the same trait for a references to the same generic type, but I don't understand how it does it.


If this is considered too trivial for those commenting, suppose I want to define a trait that not only includes addition of values and addition of references, but cross types as well. I.e how do I convert the follow code to use a trait definition as per the above:

fn some_op<T>(a: &T, b:T, c:&T) -> T 
where
             T: Add<T, Output = T> + Add<&T, Output=T>
for <'a> &'a T: Add<T, Output = T> + Add<&'a T, Output = T>
{
    (a + b) + c
}
0

There are 0 answers