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 seems to be no support for += , and x += y automatically interpreted as x = x + y (since version 1.0 alpha).

+6
source share
2 answers

Now it is 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; } } 
+7
source

You cannot at the moment, but it is definitely something very desirable. Covered by RFC No. 393 .

A very long time ago x += y was implemented as x = x + y , but it always had errors. I don’t think that at that time there were any fundamental problems with this approach, but now I think that switching to operator attributes that take arguments by value makes the noise reduction work more efficient.

+5
source

Source: https://habr.com/ru/post/981393/


All Articles