Generic traits
Just as types and functions, traits can also have generic types. As different instantiations of a type or function are considered as two separate entities, it's also the same with traits.
For example, the Add
trait uses a generic parameter for the right-hand side of the operator, which is useful if you have a type that represents an amount of change for another one, like Duration
for Instant
in the standard library.
use std::ops::Add;
struct MyInteger;
// Rhs (right-hand side) defaults to Self
impl Add for MyInteger {
type Output = MyInteger;
fn add(self, rhs: Self) -> Self::Output {
MyInteger
}
}
// Integrated conversion, please don't do this in real code!!
impl Add<MyInteger> for usize {
type Output = usize;
fn add(self, rhs: MyInteger) -> Self::Output {
self + 1
}
}