reference icon indicating copy to clipboard operation
reference copied to clipboard

Compound assignment desugaring doesn't take into account autoderef

Open theemathas opened this issue 1 month ago • 1 comments

In the reference, compound assignment expressions with non-primitive operands are described as being desugared into method calls. That is, x += y is turned into x.add_assign(y).

This desugaring is incorrect. The += form does not do autoderef, while the .add_assign form does autoderef. For example:

use std::ops::AddAssign;
fn foo<T: AddAssign<U>, U>(x: &mut &mut T, y: U) {
    // This compiles
    x.add_assign(y);
    // This doesn't compile
    x += y;
}

theemathas avatar Nov 11 '25 08:11 theemathas

I think it is more correct to say that it desugars to a fully-qualified call, e.g., AddAssign::add_sign(...), although @traviscross raised the point that the behavior may be different in the case of two-phase borrows. I'd have to review the source code in more detail to remember the full interactions.

nikomatsakis avatar Nov 18 '25 20:11 nikomatsakis