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 structsince you’re mutating it - The argument to
setproperty!should be aSymbol, not a string. It’s easy to convert a string to aSymbol, e.g.setproperty!(m, Symbol("name"), "world")but you might be better off making the keys ofmydictSymbolsinstead of strings to begin with.