Hey all, super confused by variables scope in Julia. I have the following function

Hey all, super confused by variables scope in Julia. I have the following function

function init_agents(;teams, workpatterns)::Vector{Agent}
    # print(typeof(teams), " ", typeof(workpatterns))
    for (teamname, info) in teams
        wp = workpatterns
        if haskey(info, "workpatterns")
            for (activitytype, activityspecs) in info["workpatterns"]
                wp[activitytype] = activityspecs
            end
        end
        print(teamname, " ", wporkpatterns, "\n")
    end
    return []
end

Variable wp is, I assume, a variable that only exists within the for scope, hence is reset for each iteration. However, when I update wp[activitytype] = activityspecs, it looks like it impacts the workpatterns variable itself.
My understanding is that the wp = workpatterns instruction simply creates a new reference to the workpatterns variable, hence propagating any changes made to wp to workpatterns
How can I make sure that it doesn’t? I heard about @view but not sure if it’s the correct solution here.

Note that the original poster on Slack cannot see your response here on Discourse. Consider transcribing the appropriate answer back to Slack, or pinging the poster here on Discourse so they can follow this thread.
(Original message :slack:) (More Info)

Yes, wp = workpatterns binds the name wp to the same object as workpatterns. To make wp a copy of workpatterns, write:

wp = copy(workpatterns)

Or if you also want to avoid modifications to workpatterns in case of accessing deeper levels of its structure:

wp = deepcopy(workpatterns)
1 Like