When will the original value be changed with the copied value?

I did not find the specific section of the manual that explains this, so I will try to explain it myself (but I am almost sure such section exists).

The problem I see is that your mental model on how variables and objects work is not how they work in Julia (but I am sure in other languages you would see the behavior you did expect).

In Julia, a variable is just a name for some value in some scope. When you attribute a value to some variable you are never copying it, you are binding it, this is: just giving it a name so it can be referred later (and is not collected by garbage collection in the meantime). In C/C++ and other languages, variables are specific places in memory, and when you attribute something to a variable you are always copying something, be it the value you are interested or just a pointer to it. In julia making x = y is no different than saying, “oh, this thing I am calling y right now, well, now x is another name for it”. So, when in your second example you do:

solution = ones(4)
solution_temp = solution
solution_temp = [2.,2.,2.,2.]

It can be read as:

  1. solution is the name for the return of ones(4);
  2. solution_temp is also a name for the same thing;
  3. nevermind, solution_temp is instead a name for this brand new vector or twos;
2 Likes