Accessing and changing struct fields using a dictionary

Hi, I have a struct where I to change its attributes value using a dictionary.

For example

using Agents: AbstractAgent
mutable struct Casualty <: AbstractAgent
  id :: Int
  pos :: Tuple{Int,Int,Float64}
  trauma :: Int
  awaiting_rescue :: Bool
end

@doc "Update agent attributes" ->
function update_agent_attributes!(agent::Union{Casualty,Rescuer},attr::Dict{Symbol,Any})
    for (k,v) in attr
        @show k,v 
        agent.k = v
    end 
end

a1 = Casualty(1, (775,775,0.0), 2, false)
attr = Dict(:awaiting_rescue, true)

update_agent_attributes!(a1, attr)

>>>
ERROR: type Casualty has no field k

Instead of pass the value of k, it has used k as an attribute and hence I get the no field K error.

Any ideas on how I can change the attrbute by passing values in a Dict?

for (k,v) in attr
       setfield!(agent,k,v)
end
1 Like