Implement iteration of Struct

Hi,

I’m trying to implement iteration on a small struct:

struct Coordinate
    x::Float64
    y::Float64
    Coordinate(x, y) = new(x, y)
end

So that I can unpack its members like this:

x, y = Coordinate(1,1)

Any help is welcome :slight_smile:

I think all you need to do is use

https://github.com/mauro3/UnPack.jl

2 Likes

Nice!,

But just as an excercise, it would be great to know how to do it “by hand”.

Also, the package you mention does not allow me to do

xc, yc = Coordinate(1,1)

All you need to do is fulfill the iteration interface by defining a Base.iterate method, like this one:

function Base.iterate(c::Coordinate, state = 0)
    state >= nfields(c) && return
    return Base.getfield(c, state+1), state+1
end

(Note this one actually works for any number of fields!).

You can also define other methods mentioned in the interface like

Base.length(c::Coordinate) = nfields(c)

which allows e.g. collect to work with it.

6 Likes

Just to complement this, see StaticArrays.FieldVector which is exactly for use cases like this.

2 Likes