I recently started learning rust and am exploring the type system. I am wondering if there is a way to express the following trait:
If a type
Foo
has the traitRefAddable
then two references toFoo
can be added together to produce a new (non-ref)Foo
.
searching around a bit I came across "Higher-Rank Trait Bounds" and it initially seems that this works:
use std::ops::Add;
trait RefAddable
where
for<'a> &'a Self: Add<Output = Self>,
{}
Indeed, I can only add impl RefAddable for Foo {}
if I have also implemented impl<'a> Add for &'a Foo
. However, using RefAddable
as a bound in a type seems not to have the effect I would expect.
In the following case I am presented with an error stating that it is missing the implementation of &'a T + &'a T
struct Bar<T>
where
T: RefAddable,
{
...
}
This can be fixed by adding the bound from RefAddable
to Bar
to give
struct Bar<T>
where
T: RefAddable,
for<'a> &'a T: Add<Output = T>
{
...
}
So it seems that the bound of RefAddable
isn't really expressing what I thought it was else the second bound wouldn't be needed as it would be implied by RefAddable
.
So my questions are:
- Is there a way to express the
RefAddable
trait as described above? - Why does the above implementation of
ReffAddable
not behave as I expected it would?