using DataFrames
function doit!(flag, df)
if flag==true
flag=false
end
if df[1, :flag]==true
df[1, :flag]=false
end
println("Within doit, flag=",flag,", df=",df[1, :flag])
end
function main()
df = DataFrame(flag = [true])
flag=true
for i = 1:2
println("$i - Before, flag=", flag, ", df=", df[1, :flag])
doit!(flag, df)
println("$i - After, flag=", flag, ", df=", df[1, :flag])
end
end
main()
Generates the output
1 - Before, flag=true, df=true
Within doit, flag=false, df=false
1 - After, flag=true, df=false
2 - Before, flag=true, df=false
Within doit, flag=false, df=false
2 - After, flag=true, df=false
And the docs make clear that this is the expected behaviour. It says about passing by sharing that “modifications to mutable values (such as Array
s) made within a function will be visible to the caller.” It also gives an example of how asigining a new value to a simple (numeric) parameter “changes the binding (“name”) to refer to a new value”.
So, two questions:
- Why don’t simple variables mutate like arrays? What other types have this non-mutating behaviour.
- Can I cause simple parameters to mutate in the same way as arrays or is this not possible. (I realise I could simply return the changed value).
Thanks,
Tim