How can I use compound operators like "+=" with custom types?
Overloading some basic operators is possible by implementing Add, Sub, etc. But there does not appear to be any support for +=, neither is x += y automatically interpreted as x = x + y (as of the 1.0 alpha release).
This is now supported, called AddAssign (SubAssign, MulAssign... etc).
This is a basic example:
use std::ops::{Add, AddAssign};
struct Float2(f64, f64);
impl AddAssign for Float2 {
fn add_assign(&mut self, rhs: Float2) {
self.0 += rhs.0;
self.1 += rhs.1;
}
}
You can't, at the moment but it's definitely something much desired. Covered by RFC issue #393.
A very long time ago x += y was implemented as x = x + y but there was always bugs in it. I don't think any were fundamental problems with the approach at the time, but now I think the switch to the operator traits taking the arguments by-value makes that desugaring harder to work well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With