4

I'm stuck with this code for operator overloading.

use std::ops::Add;

struct Test<T: Add>{
    m:T
}

impl<T:Add> Add for Test<T>{
    type Output = Test<T>;
    fn add(self, rhs: Test<T>) -> Test<T> {
        Test { m: (self.m + rhs.m) as T }
    }
}

I cannot cast (self.m + rhs.m) to T because it is a non-scalar cast.

Is there a trait for types scalar-castable to T?

ljedrz
  • 20,316
  • 4
  • 69
  • 97
equal-l2
  • 899
  • 7
  • 17

1 Answers1

4

No, there isn't a trait covering this functionality. Only some casts are possible and their full list can be found in The Book.

As for your Add implementation, you should modify it in the following manner in order for it to work:

use std::ops::Add;

struct Test<T: Add>{
    m: T
}

impl<T> Add for Test<T> where T: Add<Output = T> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        Test { m: self.m + rhs.m }
    }
}

You can find a good explanation why the additional T: Add<Output = T> bound is necessary in this SO answer. This one might be even closer to your exact case.

Community
  • 1
  • 1
ljedrz
  • 20,316
  • 4
  • 69
  • 97