Amro
August 31, 2021, 12:37pm
1
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
nilshg
August 31, 2021, 12:39pm
2
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
jling
August 31, 2021, 12:51pm
3
nilshg:
fieldnames(typeof(x))
I low key suspect this will be slow
1 Like
nilshg
August 31, 2021, 1:01pm
4
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
jling
August 31, 2021, 1:06pm
5
we do have aggressive constant prop for sure…
1 Like
DNF
August 31, 2021, 1:12pm
6
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)
6 Likes