How can an operator be overloaded for different RHS types and return values?

后端 未结 2 832
既然无缘
既然无缘 2020-12-01 16:19

Given the following struct:

struct Vector3D {
    x: f32,
    y: f32,
    z: f32
}

I want to overload its * operator to do a d

2条回答
  •  Happy的楠姐
    2020-12-01 16:28

    As of Rust 1.0, you can now implement this:

    use std::ops::Mul;
    
    #[derive(Copy, Clone, PartialEq, Debug)]
    struct Vector3D {
        x: f32,
        y: f32,
        z: f32,
    }
    
    // Multiplication with scalar
    impl Mul for Vector3D {
        type Output = Vector3D;
    
        fn mul(self, f: f32) -> Vector3D {
            Vector3D {
                x: self.x * f,
                y: self.y * f,
                z: self.z * f,
            }
        }
    }
    
    // Multiplication with vector, aka dot product
    impl Mul for Vector3D {
        type Output = f32;
    
        fn mul(self, other: Vector3D) -> f32 {
            self.x * other.x + self.y * other.y + self.z * other.z
        }
    }
    
    fn main() {
        let a = Vector3D {
            x: 1.0,
            y: 2.0,
            z: 3.0,
        };
        let b = a * -1.0;
        let c = a * b;
    
        println!("{:?}", a);
        println!("{:?}", b);
        println!("{:?}", c);
    }
    

    The big change that allows this is the introduction of associated types, which shows up as the type Output = bit in each implementation. Another notable change is that the operator traits now take arguments by value, consuming them, so I went ahead and implemented Copy for the struct.

提交回复
热议问题