1

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 trait RefAddable then two references to Foo 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?
Ryan
  • 51
  • 6
  • 1
    Does this answer your question? [Why is it necessary to add redundant trait bounds even though my trait uses those same traits as bounds?](https://stackoverflow.com/questions/49434716/why-is-it-necessary-to-add-redundant-trait-bounds-even-though-my-trait-uses-thos) – Mihir Luthra Oct 20 '21 at 07:17

0 Answers0