How to define a function such that its arguments can mutate?

That example will not work because numbers are immutable.
A good resource to read is the official documentation. In particular, the frequently asked questions in the docs say:

In Julia, the binding of a variable x cannot be changed by passing x as an argument to a function. When calling change_value!(x) in the above example, y is a newly created variable, bound initially to the value of x , i.e. 10 ; then y is rebound to the constant 17 , while the variable x of the outer scope is left untouched.

However, if x is bound to an object of type Array (or any other mutable type). From within the function, you cannot “unbind” x from this Array, but you can change its content. For example:

You can also go the manual in the functions section, where it mentions that modifications to a mutable container will be visible from the outside.

Numbers are not a mutable container, so you cannot change their value from inside a function. What you could do if you want something like that is to use the Ref trick from one of your other posts. Another choice is to create a mutable composite type that contains the variable you wish to modify.

6 Likes