Reputation: 19502
I have a struct (and some methods) like this:
pub struct Foo<T> where T:Ord+Add+Sub {
bar: T,
baz: T,
// ...
}
I need to do some numeric operations (addition, subtraction etc) and store the results. The documentation states that the result in the Sub
or Add
traits may be yet another type.
Upvotes: 1
Views: 355
Reputation: 299810
If you look at the Add
trait you will see:
pub trait Add<RHS = Self> {
type Output;
fn add(self, rhs: RHS) -> Self::Output;
}
This is the flexibility required to specify the result type depending on both the Left and Right arguments to +
.
If you wish to constrain your Foo<T>
structure to T
for which there exists a symmetric implementation of T
which itself returns T
, you can do so in the where
clause:
T
can be added to T
, T
must implement Add<T>
(which, since RHS
defaults to Self
, is the same as implementing Add
)T
, T
must implement Add<Output = T>
(the associated type syntax)A similar principle applies to Sub
, giving:
struct Foo<T>
where T: Ord + Add<Output = T> + Sub<Output = T>
{
...
}
Upvotes: 4
Reputation:
I don't know what you mean by "numeric type", but this is how you constrain the type such that addition and subtraction yield T
:
pub struct Foo<T> where T: Ord+Add<Output=T>+Sub<Output=T> {
...
}
Upvotes: 1