Access a struct field from a string

The foo.bar syntax only works if “bar” is the actual name of the field, not a variable holding the name of the field. Instead, you want the setproperty! function, which takes the field name as an argument:

julia> mutable struct MyStruct
         name::String
       end

julia> m = MyStruct("hello")
MyStruct("hello")

julia> field = :name
:name

julia> setproperty!(m, field, "world")
"world"

julia> m
MyStruct("world")

A few things to note:

  • Your struct must be a mutable struct since you’re mutating it
  • The argument to setproperty! should be a Symbol, not a string. It’s easy to convert a string to a Symbol, e.g. setproperty!(m, Symbol("name"), "world") but you might be better off making the keys of mydict Symbols instead of strings to begin with.
5 Likes