How to overload +=?

Is it possible to overload +=?

mutable struct A
    a::Int
end

function Base.:+=(a::A, b::A)
  a.a += b.a
  a
end

EDIT: As pointed out by @giordano in post 7, the struct A should be defined immutable:

struct A
    a::Int
end

You can’t overload assignment, but I think it’s enough in this case to overload + and += will come for free.

1 Like

Thank you for the quick reply but it does not seem to work:

julia> Base.:+(a::A, b::A) = A(a.a+b.a)

julia> A(2) + A(3)
A(5)

julia> A(2) += A(3)
ERROR: syntax: invalid assignment location "A(2)" around REPL[12]:1
Stacktrace:
 [1] top-level scope
   @ REPL[12]:1
x = A(2)
x += A(3)
A(5)
2 Likes

This is basically the same as

julia> 1 += 2

which of course doesn’t work.

1 Like

:man_facepalming: Thank you.

1 Like

Note that this wouldn’t mutate the argument (which one?), in case this is what you were expecting, since you marked the type as mutable.

But the sum should not mutate neither argument: it is only += that should. Am I wrong?

Assignment, including +=, never mutates. Is this what you were expecting?

3 Likes