I have a minus
function which leads to a use of moved value: 'scalar'
compile error, which makes sense.
struct Point<T> {
x: T,
y: T,
z: T,
}
impl<T: Sub<Output = T>> Point<T> {
//subtract scalar value from all Point fields.
fn minus(self, scalar: T) -> Self {
Point {
x: self.x - scalar,
y: self.y - scalar,
z: self.z - scalar,
}
}
}
Solution 1
Make the type T
cloneable. It fixes this but it seems like very expensive operation because it's copying the scalar value for each field. Is there another less expensive solution?
impl<T: Sub<Output = T> + Clone> Point<T> {
fn minus(self, scalar: T) -> Self {
Point {
x: self.x - scalar.clone(),
y: self.y - scalar.clone(),
z: self.z - scalar.clone(),
}
}
}
Attempted solution 2
I thought maybe I can use references. But then I get cannot subtract '&T' from '&T'
, which I don't understand.
Is there a more efficient way to do this that doesn't Clone
or Copy
the input scalar
value?
impl<T: Sub<Output=T>> Point<T> {
fn minus(self, scalar: &T) -> Self {
Point {
x: &self.x - scalar,
y: &self.y - scalar,
z: &self.z - scalar,
}
}
}