Access struct fields within a function by string argument

2885 views julia-lang
7

Say I have a struct,

struct MyStruct

a
b

end

Is there some way to write a function like the following

function doSomething(x::MyStruct,fieldName::String)

y = x.fieldName

return f(y)

end

I could not find anything about this in the documentation / forums.

answered question

1 Answer

6

You can access fields with Symbols, so you can convert the string to a symbol and then use getproperty:

julia> struct MyStruct
           a
           b
       end

julia> function doSomething(x::MyStruct, name::String)
           s = Symbol(name)
           return getproperty(x, s)
       end
doSomething (generic function with 1 method)

julia> doSomething(MyStruct(1, 2), "a")
1

Note, however, that this will probably be very inefficient, since the compiler most likely can't see through this and thus your code might be type-unstable, see https://docs.julialang.org/en/v1/manual/performance-tips/.

posted this

Have an answer?

JD

Please login first before posting an answer.