# Sum elements of a struct

How can I sum the elements of MyStruct?

Code:

``````struct MyStruct
a::Int
b::SVector{N_lds, Int64}
c::Int
end

import Base: -
-(x::MyStruct, y::MyStruct) = MyStruct(x.a - y.a, x.b .- y.b, x.c - y.c)
v1 = MyStruct(16, [0, 0, 1], 1)
v2 = MyStruct(15, [5, 6, 1], 1)
fg = v1 -v2

sum(fg)
``````

ERROR: MethodError: no method matching iterate(::MyStruct)

What do you want `sum(MyStruct)` to return?

``````v2 = MyStruct(15, [5, 6, 1], 1)
``````

should it return `28`?

No, the sum of the elements of fg. Should be -10.

I mean, should `sum(v2)` return `28`?

yes

Okay, given that you know how to overload `Base.-`, it should be easy to write code to overwrite `Base.sum`.

But if you want `sum` to work automatically, you should write a method for `iterate`. If you were to count through the elements of `MyStruct`, would would that be a meaningful thing to do? In a mathematical sense. This is dependent on what `MyStruct` represents.

1 Like

Unless this is a toy example, this is probably not the recommended course of action and will come back to bite you in the future.

2 Likes

This seems like an XY problem. What are you actually trying to represent with your data structure here?

3 Likes