A simple MWE:
mutable struct MyHuman age::Int64 MyHuman(i) = new(i) end # create an array A = [MyHuman(i) for i = 1:100] # let's replace the 1st element of A by a new object change_element(A) function change_element(a::MyHuman) # check if the incoming argument refers to the same object println("equal before?: $(a === A)") ## true a = MyHuman() a.age = 100000 println("equal after?: $(a === A)") ## false!!! end #A.age NEVER CHANGES! because I think it creates a new object in memory
Basically I have an
Array of my custom type. I would like to pass in object
A and essentially replace this object with a new instance of the type.
For more context, consider an agent-based model where agents have an age. After a certain age, the agent dies. To maintain a constant population, I would like to replace the dead agent by a brand new agent in it’s place.
I understand that I don’t have to run the
a = MyHuman() as this creates a new object in memory and reassigns my variable
a. I could manually just update the fields of this person, but this will involve repeating code. In reality my
MyHuman() type has many fields, and the constructor has certain logic that needs to be followed.
Edit: I guess if I pass in the entire array and reassign
A = MyHuman() it would work, but I’d like the function to act on a single object rather than the whole array.