Derive macros for AddAssign etc.?

I guess this comes under internals (libraries):

Is it possible to add derive macros for AddAssign etc.?

Status quo: arithmetic operations are supported on custom types via the Add, Sub, Mul etc. traits. These can be implemented multiple times (e.g. to component-wise operations on vectors by scalars), which adds up to many implementations already.

Now to support += etc. for these, the number of trait implementations needs to be doubled.


Note that as with derive(Debug), an error would be emitted when the corresponding trait (Add etc.) wasn't implemented. I don't see any technical hurdles.

Alternatively, I guess the plan may be to add blanket implementations once specialisation is stable — however, I understand this is likely to be a ways off yet.

1 Like

There is the derive_more crate which includes derives for things like Add and AddAssign. But I think they are different from your suggestion, as they do the operations on the individual fields. That is, I think you're hinting at

impl OpAssign for T {
    fn op_assign(&mut self, rhs: T) {
        *self = self.op(rhs);
    }
}

while derive_more does it like

impl OpAssign for T {
    fn op_assign(&mut self, rhs: T) {
        self.0.op_assign(rhs.0);
        self.1.op_assign(rhs.1);
    }
}
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.