Overload in place =

I have a custom type that looks like this

struct foo{T}

A1::Array{T}
A2::Array{T}

end

function Base.:+(x:: foo, y:: foo)

return foo(x.A1 + y.A1, x.A2 + y.A2)

end

function Base.:.=(x:: foo, y:: foo)

x.A1 .= y.A1
x.A2 .= y.A2

end


And I would like to do a in place operation like

foo1 = foo(rand(10), rand(10))
foo2 = foo(rand(10), rand(10))

foo1 .= foo1 + foo2

But I’m pretty sure that will create an extra foo struct and I’m not really sure how to implement the equivalent to

A = rand(10)
B = rand(10)
A .= A .+ B

If you’re willing to give up the + syntax, you could define an in place add!(x::foo, y::foo) that modifies x.

function add!(x::foo, y::foo)
    x.A1 .+= y.A1
    x.A2 .+= y.A2
    return x
end

I would rather not give up the syntax! I’m implementing my struct so that it behaves like a normal array.
Maybe making it so that foo <: AbstractArray will solve it?

I think you need to overload broadcast!

Arrays · The Julia Language!

1 Like

See also Functions · The Julia Language

The documentation on overloading broadcasting can be found here:

https://docs.julialang.org/en/v1/manual/interfaces/#man-interfaces-broadcasting

2 Likes