Is there a property of scalar cast types?

I am stuck with this code to overload the operator.

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 drop (self.m + rhs.m) in T because it is a non-scalar cast .

Is there a property for types scalar to T ?

+3
generics traits rust
source share
1 answer

No, there are no features covering this functionality. Only some throws are possible, and a complete list can be found in The Book .

As for your implementation of Add , you should modify it as follows so that it works:

 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 an additional T: Add<Output = T> binding T: Add<Output = T> needed in this SO answer . This may be even closer to your specific case.

+4
source share

All Articles