Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I overload the += "plus equals" operator?

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).

like image 814
dhardy Avatar asked Jan 22 '15 11:01

dhardy


2 Answers

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;
    }
}
like image 81
ideasman42 Avatar answered Nov 01 '22 11:11

ideasman42


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.

like image 35
huon Avatar answered Nov 01 '22 09:11

huon