I am using the Parameters package to do some work. One of the parameters is an array and surprisingly the struct gets changed when I give it as an argument to a function that modify the array after unpacking
using Parameters
@with_kw struct MyStruct
x::Array{Float64,1} = zeros(N)
end
function noModify(structIn::MyStruct)
@unpack x = structIn
x = ones(N)
end
function yesModify(structIn::MyStruct)
@unpack x = structIn
for i=1:N
x[i] = 2.0
end
end
N = 10
exampleStruct = MyStruct()
println(exampleStruct.x)
noModify(exampleStruct)
println(exampleStruct.x)
yesModify(exampleStruct)
println(exampleStruct.x)
@unpack x = exampleStruct
x = 3 * ones(N)
println(exampleStruct.x)
for i=1:N
x[i] = 4.0
end
println(exampleStruct.x)
It runs as
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
[2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0]
[2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0]
[2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0]
As expected the function noModify
doesn’t modify the global variable exampleStruct
.
What I found weird is that the function yesModify
does!
Of course doing it directly in the global scope doesn’t change anything. The only case that is unexpected for me is the one in the function yesModify
that has a for loop inside.
Am I missing something? is that something that is supposed to happen? I thought that even if I unpack something and modify it, the orignal structure (called exampleStruct
in this case) should not change.