I want to Add and Sub on a tuple. The simple implementation doesn't seem to work.
impl Add for (u32, u32) {
type Output = (u32, u32);
fn add(self, other: Self) -> Self::Output {
(self.0 + other.0, self.1 + other.1)
}
}
It would be a lot of boilerplate to do this for every primitive. How could I do this with generics and write one implementation for every primitive (or other object) that already implements std::ops::Add
Rust doesn’t allow you to create your own operators or overload arbitrary operators. But you can overload the operations and corresponding traits listed in std::ops by implementing the traits associated with the operator.
Only traits defined in the current crate can be implemented for arbitrary types.
So my solution is to use tuple struct struct My2<T>(T, T);:
use std::ops::Add;
#[derive(Debug, PartialEq)]
struct My2<T>(T, T);
impl<T: Add<Output = T>> Add for My2<T> {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
Self(self.0 + other.0, self.1 + other.1)
}
}
fn main() {
assert_eq!(My2(1, 0) + My2(2, 3), My2(3, 3));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With