Calling struct fields with symbol or string

Hi all,
I got to the problem how to call field names in a struct automatically with symbols or strings.
This can be solved manually with if-else-constructions but is quite long and error-prone.

Beside some related topics like Dictionaries and var"varname" I finally found a way to do this with getproperty()

Previousely I had:

struct MyABCD
	var_a
	var_b
	var_c
	var_d
end

myabcd = MyABCD(1,2,3,4)

mysym = :c # Call variable 'c' 

data = 0 # Copy the value of var_c to data

if mysym == :a
	data = myabcd.var_a
elseif mysym == :b
	data = myabcd.var_b
elseif mysym == :c
	data = myabcd.var_c
elseif mysym == :d
	data = myabcd.var_d
end

Instead of the if-else construction now I use:

data2 = 0
var_sym = Symbol("var_",string(mysym))
data2 = getproperty(myabcd, var_sym)

If you want to access a struct field you may use setproperty!()

For more information see:

If you want to use strings, you can even overload getproperty to work with Strings.

               var_a
               var_b
               var_c
               var_d
       end

julia> myabcd = MyABCD(1,2,3,4)
MyABCD(1, 2, 3, 4)

julia> import Base.getproperty

julia> getproperty(m::MyABCD, s::String) = getproperty(m, Symbol(s));

julia> getproperty(myabcd, "var_a")
1
1 Like

Just note there is a good chance your field access becomes slower than usual. Are you sure this is necessary?

3 Likes

Right, if you are looking to do this frequently, you probably want a Dict or similar, not a struct.

4 Likes