dhardy
dhardy

Reputation: 12154

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

Upvotes: 13

Views: 5469

Answers (2)

ideasman42
ideasman42

Reputation: 48028

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;
    }
}

Upvotes: 17

huon
huon

Reputation: 102066

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.

Upvotes: 4

Related Questions