I’d like to be able to add two structs without knowing about the structs ahead of time, such as:
function Base.:+(a::T, b::T) where {T}
T((getfield(a, field) + getfield(b, field) for field in fieldnames(a))...)
end
I find that for a simple struct (with an int and a float) that this takes about a microsecond, which is much longer than I expected.
I also tried it this way with mutable structs:
function Base.:+(a::T, b::T) where {T}
s = deepcopy(a)
for field in fieldnames(a)
setfield!(s, field, getfield(a, field) + getfield(b, field))
end
return s
end
That takes about 2us.
If I hard-code the addition, like so:
addem(x::MyType, y::MyType) = MyType(x.a + y.a, x.b + y.b)
it only takes about 20ns. This is more like what I’m hoping for, but without hard-coding the addition.
Is there a better way to do this generally?