How to update scalar and Boolean in-place?

I have function update2 which returns the values of status, nChange. However, I need to build function update1 which update status, nChange without returning their values (in-place mutation) but it seems not correct process. How can I implement that correctly?


using SparseArrays, LinearAlgebra

function update1(status, nChange, check)
       if check == 1
              status = true;
              nChange += 1;
       end
end

function update2(status, nChange, check)
       if check == 1
              status = true;
              nChange += 1;
       end
       status, nChange;
end

function run1()
       status = false;
       nChange = 0;
       check = 1;
       update1(status, nChange, check)
       status, nChange;
end

function run2()
       status = false;
       nChange = 0;
       check = 1;
       status, nChange = update2(status, nChange, check)
       status, nChange;
end

status1, nChange1 = run1()
status2, nChange2 = run2()

julia> status1
false

julia> nChange1
0

julia> status2
true

julia> nChange2
1

Use a Ref()

julia> function update!(x)
           x[] += 1
       end;

julia> y = Ref(1)
Base.RefValue{Int64}(1)

julia> update!(y);

julia> y
Base.RefValue{Int64}(2)
1 Like

Ints and Bools, and all other Numbers, and many, many other types are immutable, so you cannot update them.

Updating objects of mutable type is possible, though, so wrapping your value in a mutable type like Ref will work.

But even if you have a mutable object, doing this

will not mutate them, the above only rebinds the variables, and it will not be visible outside the function.

2 Likes

Thank you very much I got it!