Are there any ways to implement a trait for multiple generic types?

For example this code below where Color has r, g, b which are all f64s: (Let's assume the add trait is implement for multiplications between f64s and f32s)

impl ops::Mul<f64> for Color {
    type Output = Color;

    fn mul(self, other: f64) -> Self::Output {
        Color {
            r: self.r * other,
            g: self.g * other,
            b: self.b * other,
        }
    }
}

impl ops::Mul<f32> for Color {
    type Output = Color;

    fn mul(self, other: f32) -> Self::Output {
        Color {
            r: self.r * other,
            g: self.g * other,
            b: self.b * other,
        }
    }
}

Is there any way to condense it into one implementation? Example:

impl ops::Mul<f64 || f32> for Color {
    type Output = Color;

    fn mul(self, other: f64 || f32) -> Self::Output {
        Color {
            r: self.r * other,
            g: self.g * other,
            b: self.b * other,
        }
    }
}

The main two ways are macros and a blanket implementation based on trait bounds.

Examples.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.