1

Say I want to write a function that makes all bools false:

function true_to_false!(boolean::Bool)
    boolean = false
end

Why can I then not use this to change the values of another function? e.g.:

function make_x_false()
    x = true
    true_to_false!(x)
    return x
end

Returns true.

Of course there are workarounds such as

function make_x_false()
    x = true
    x = true_to_false!(x) 
end

and

function make_x_false!(x)
    x = true_to_false!(x) 
end

But I have a case where these would make for some very messy code!

Thanks,

cj wyett
  • 152
  • 6

1 Answers1

3

Julia is using pass-by-sharing mechanism see also How to pass an object by reference and value in Julia?

In practice this means that a function can mutate its argument when it is a mutable struct, Dict or an Array but primitive types cannot be mutated - they are just recreated inside the function.

Hence you can use for an example Ref do achieve the desired effect:

julia> function  make_x_false!(x::Ref{Bool})
           x[] = false
       end;


julia> u = Ref{Bool}(true)
Base.RefValue{Bool}(true)


julia> u[]
true

julia> make_x_false!(u);

julia> u[]
false
Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62