I'm trying to implement the Add
trait for anything that implements another trait (in the example code the Test
trait). I'm using references in the Add
implementation because not everything that implements Test
will be the same size. The code below compiles fine:
use std::ops::Add;
struct Foo(i32);
struct Bar(i64);
trait Test {}
impl Test for Foo {}
impl Test for Bar {}
impl<'a, 'b> Add<&'b Test> for &'a Test {
type Output = Box<Test>;
fn add(self, other: &'b Test) -> Box<Test> {
if true {
Box::new(Foo(5))
} else {
Box::new(Bar(5))
}
}
}
When I try to actually use Add
, as below, it says that the operation could not be applied because the implementation of Add
for &Foo
is missing.
fn test_add() {
&Foo(5) + &Bar(5)
}
Have I defined the implementation incorrectly? Have I called it incorrectly? The goal is to make the function add take two references to objects which both implement Test
, and return a reference (or box) to a new object that implements Test
(and might not be the same underlying type as either of the inputs).