Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic implementation for std::ops on tuples

Tags:

generics

rust

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

like image 689
sbstnzmr Avatar asked Nov 21 '25 15:11

sbstnzmr


1 Answers

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));
}
like image 54
wasmup Avatar answered Nov 24 '25 16:11

wasmup