1

I'm trying to create a trait which is the amalgamation of other traits, but with their inputs over the borrowed versions of those values instead of taking ownership of them. For this example I reduced it to one.

For instance:

use std::ops::Add;

trait Foo
where
    for<'a> &'a Self: Add<Output = Self>,
{
}

It seems like this should create a trait Foo where it needs Add to be defined. However, this doesn't seem to work when I attempt to use it.

#[derive(Debug)]
struct Two<T> {
    x: T,
    y: T,
}

impl<T> Two<T> where T: Foo {}

This doesn't compile with the error:

error[E0277]: cannot add `&'a T` to `&'a T`
  --> src/main.rs:15:1
   |
15 | impl<T> Two<T> where T: Foo {}
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no implementation for `&'a T + &'a T`
   |
   = help: the trait `for<'a> std::ops::Add` is not implemented for `&'a T`
   = help: consider adding a `where for<'a> &'a T: std::ops::Add` bound
note: required by `Foo`
  --> src/main.rs:3:3
   |
3  | /   trait Foo
4  | | where
5  | |     for<'a> &'a Self: Add<Output = Self>,
6  | | {
7  | | }
   | |_^

Why do I need that clause if T requires Foo which itself has that requirement? Is there some other way to create an amalgamation trait to get better efficiency?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
coltfred
  • 1,470
  • 9
  • 17
  • 3
    I believe your question is answered by the answers of [How to write a trait bound for a reference to an associated type on the trait itself?](https://stackoverflow.com/q/50090578/155423) and/or [Why are supertrait bounds other than the first not recognized on an associated type?](https://stackoverflow.com/q/50660911/155423). If you disagree, please [edit] your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Jul 10 '18 at 23:30
  • 2
    TL;DR: it's a compiler shortcoming, you have to replicate the bounds for now. – Shepmaster Jul 10 '18 at 23:30
  • I didn't think of searching for super trait. Thanks for the answers. I guess I'll limp along until the bug is fixed. – coltfred Jul 11 '18 at 14:32

0 Answers0