Can fields of structure be indexed by number?

It is know that accessing a field of structure is by using the dot method. Such as, accessing the first field of the below structure is Point.x. However, I would like to access the fields by using a index number accompanied to the name of structure (i.e. as in matrix).
For example instead of using Point.x, I need to use something like Point(1) or Point[1]. Any way to do so?

struct Point
   x :: Int
   y :: Int
end

I guess you could define a getindex method for your struct like this:

julia> struct Point
        x::Int
        y::Int
       end

julia> Base.getindex(x::Point, i) = getproperty(x, fieldnames(typeof(x))[i])

julia> a = Point(10, 20)
Point(10, 20)

julia> a[1]
10

julia> a[2]
20
2 Likes

I low key suspect this will be slow

1 Like

Not sure how to benchmark this properly, seems everything is figured out by the compiler:

julia> @btime $a[2]
  0.001 ns (0 allocations: 0 bytes)
20
3 Likes

we do have aggressive constant prop for sure…

1 Like

It looks to me like you should subtype FieldVector from the StaticArrays package: API · StaticArrays.jl

This looks like a classic application of this. You will get lots of functionality for free, and excellent performance.

And if you want to implement it yourself, you could study its source code.

2 Likes

Wouldn’t the best be Base.getindex(x::Point, i::Int) = getfield(x, i)

5 Likes