Overflow evaluating the requirement u32: Mul

hello! i'm trying to implement my own vector3 type, but i can't get multiplication with a number to work. my code (MRE) looks like this:

#[derive(Eq, PartialEq, Debug, Copy, Clone)]
pub struct Vec3<T> {
    pub x: T,
    pub y: T,
    pub z: T,
}

impl<T: Mul<Output = T>> Mul for T {
    type Output = Vec3<T>;

    fn mul(self, rhs: Vec3<T>) -> Self::Output {
        Self {
            x: self.x * rhs,
            y: self.y * rhs,
            z: self.z * rhs,
        }
    }
}

the error states the following:

error[E0275]: overflow evaluating the requirement `u32: Mul`
   |
   = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`glass`)
note: required for `u32` to implement `Mul`
  --> src/math/vec.rs:34:26
   |
34 | impl<T: Mul<Output = T>> Mul for T {
   |             ----------   ^^^     ^
   |             |
   |             unsatisfied trait bound introduced here
   = note: 126 redundant requirements hidden
   = note: required for `u32` to implement `Mul`

For more information about this error, try `rustc --explain E0275`.

does anyone have any idea how to fix it? i tried the recursion limit thing, but it just increases the number in the error everytime I set it to it.

I think what you want is this:

-impl<T: Mul<Output = T>> Mul for T {
+impl<T: Mul<Output = T>> Mul<Vec3<T>> for T {

but if you do this, you’ll run into a different error:

   |
10 | impl<T: Mul<Output = T>> Mul<Vec3<T>> for T {
   |      ^ type parameter `T` must be covered by another type when it appears before the first local  type (`Vec3<T>`)
   |

= note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local, and no uncovered type parameters appear before that first local type

= note: in this case, 'before' refers to the following order: impl<..> ForeignTrait<T1, ..., Tn> for T0, where T0 is the first and Tn is the last

The “orphan rule” will not allow you to implement traits defined outside your crate for types defined outside your crate. You can implement Mul<T> for Vec3<T> but not the other way around.

This works!

impl<T: Mul<Output = T> + Copy> Mul<T> for Vec3<T> {
    type Output = Vec3<T>;

    fn mul(self, rhs: T) -> Self::Output {
        Self {
            x: self.x * rhs,
            y: self.y * rhs,
            z: self.z * rhs,
        }
    }
}

I completely forgot the orphan rule and that Mul had a generic type parameter.
Thanks!

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.