I'm writing an application in Rust that will have to use vector arithmetic intensively and I stumbled upon a problem of designing operator overload for a structure type.
So I have a vector structure like that:
struct Vector3d {
pub x: f64,
pub y: f64,
pub z: f64,
}
and I want to be able to write something like that:
let x = Vector3d {x: 1.0, y: 0.0, z: 0.0};
let y = Vector3d {x: -1.0, y: 0.0, z: 0.0};
let u = x + y;
As far as I can see, there are three different ways to do it:
Implement
std::ops::Add
trait forVector3d
directly. That works, but this trait's method signature is:fn add(self, other: Vector3d)
So it will invalidate its arguments after usage (because it moves them) which is undesirable in my case since many vectors will be used in multiple expressions.
Implement
Add
trait forVector3d
and also implement theCopy
trait. This works, but I feel iffy on that sinceVector3d
isn't exactly a lightweight thing (24 bytes at least) that can be copied quickly, especially when there are many calls to arithmetic functions.Implement
Add
for references toVector3d
, as suggested here. This works, but in order to apply the operator, I will have to writelet u = &x + &y;
I don't like this notation because it doesn't exactly looks like its mathematic equivalent, just u = x + y
.
I'm not sure which variant is optimal. So, the question is: is there a way to overload the '+' operator in such a way that
- It accepts its arguments as references instead of copying or moving them;
- It allows to write just
u = x + y
instead ofu = &x + &y
?