I am trying to implement a basic Polynomial type in Rust, with overloaded operators for the math operations. So far, I could manage to implement the basic operations like addition, subtraction, etc. by overloading the operators. The problem is, I would like to take operands by reference to avoid unnecessary copies. Ie. :
impl ops::Add for &Polynomial {
type Output = Polynomial;
fn add(self, other: Self) -> Polynomial {
let mut result = self.clone();
for (power, coeff) in other.coefficients.iter().enumerate() {
result.add_coeff(power, *coeff);
}
result
}
}
impl ops::Sub for &Polynomial {
// Implementation
// ...
}
impl ops::Mul for &Polynomial {
// Implementation
// ...
}
// Etc.
This works as expected, however it forces the user to borrow the operands explicitly each time, which becomes less readable as the expressions become more complex :
let (quotient, remainder) = p2.div_rem(&p1);
assert_eq!(&("ient * &p1) + &remainder, p2);
// Even worse example found on the internet.
// Note that you need to explicitly borrow each and every intermediate result :
let result = &(&(&a * &b) + &(&c * &d)) / 2;
Instead of the last two lines, I think it would be much cleaner and readable if I could just write :
assert_eq!(quotient * p1 + remainder, p2);
let result = (a * b + c * d) / 2;
…and let the borrow happen « automatically » (just like it does when you call a method which has a &self as its first parameter on any value : it is automatically and implicitly borrowed without having to explicitly borrow it).
However I don’t know if it is possible to do, or how ?