If you plan to get the value only few times redrikekre's solution is OK. However, using metaprogramming you can write code without efficiency penalty, see the getDoSomething2()
function below.
Consider those three functions:
function doSomethingNative(x)
return x.a
end
function doSomething(x, name::String)
return getproperty(x, Symbol(name))
end
function getDoSomething2(name::String)
field = Symbol(name)
code = quote
(obj) -> obj.$field
end
return eval(code)
end
Now the setup:
using BenchmarkTools
struct MyStruct
a
b
end
x = MyStruct(5,6)
Now the benchmarks:
julia> @btime doSomethingNative($x)
0.001 ns (0 allocations: 0 bytes)
5
julia> @btime doSomething($x,"a")
36.266 ns (0 allocations: 0 bytes)
5
julia> const doSomething2 = getDoSomething2("a");
julia> @btime doSomething2($x)
0.001 ns (0 allocations: 0 bytes)
5
If you run @code_native doSomethingNative(x)
and @code_native doSomething2(x)
you will see that the assembly output is identical.