I'm writing a ray-tracer and I want to be able to subtract my 3D vectors:
use std::ops::Sub;
#[derive(Clone, Debug)]
pub struct Vec3 {
pub v: [f64; 3],
}
impl Sub for Vec3 {
type Output = Vec3;
fn sub(self, other: Vec3) -> Vec3 {
Vec3 {
v: [
self.v[0] - other.v[0],
self.v[1] - other.v[1],
self.v[2] - other.v[2],
],
}
}
}
This seems to work. However, when I try to use it:
fn main() {
let x = Vec3 { v: [0., 0., 0.] };
let y = Vec3 { v: [0., 0., 0.] };
let a = x - y;
let b = x - y;
}
I get complaints from the compiler:
error[E0382]: use of moved value: `x`
--> src/main.rs:26:13
|
25 | let a = x - y;
| - value moved here
26 | let b = x - y;
| ^ value used here after move
|
= note: move occurs because `x` has type `Vec3`, which does not implement the `Copy` trait
error[E0382]: use of moved value: `y`
--> src/main.rs:26:17
|
25 | let a = x - y;
| - value moved here
26 | let b = x - y;
| ^ value used here after move
|
= note: move occurs because `y` has type `Vec3`, which does not implement the `Copy` trait
How can I write the subtraction operator so that the code above works?
Please don't tell me I should an existing 3D math module. I'm sure there's something better, but I'm after learning how to do it myself to learn the language.
How do I implement the Add trait for a reference to a struct? doesn't help as it requires specifying lifetimes for object which I'm not at yet.