Suppose I want a struct
that has to store a variable which can be quite general. Most typically, it will contain an array of forces
, or alternatively an energy
value. Something like:
struct System{T}
property::T
end
The user initializes the system
with:
forces = zeros(10)
system = System(forces)
That is fine, and now he/she can access the forces using…
system.property
Is there a way to overload getproperty
in such a way that the user is able to retrieve the forces
using
system.forces
?
Note that he/she could also have started with:
energy = 0.0
system = System(energy)
And now I would like that system.energy
retrieved the system.property
value, as well.
(ps: If I need a macro for this - which obviously can do the trick, let it go, I prefer to avoid macros).
Edit:
The best I could do so far is to define an additinal field property_name
, and use something like:
julia> struct System{T}
property_name::Symbol
property::T
end
julia> function Base.getproperty(s::System, a::Symbol)
if a == getfield(s, :property_name)
return getfield(s, :property)
else
return getfield(s, a)
end
end
julia> s = System(:energy, 0.0)
System{Float64}(:energy, 0.0)
julia> s.energy
0.0
Not too bad, but somewhat redundant. I guess I won’t be able to do that better without a macro, as no function will be able to access the name of the incoming variable.