Mutable struct pitfall

Fair enough. I think Java has similar behavior but they use the keyword class instead. If you want to think in terms of C structs, maybe the most sane analogy is that the problem is not the struct itself (mutable or immutable), but that all variables in Julia are NOT names of positions of memory, but instead, names of pointers to the memory. So, if your swap two variables i.e., a, b = b, a you just swap pointers instead (often you do not even pay the price of a pointer swap, the compiler elides this).

This is the best I can do using concepts of C, the truly best would be learning how Julia has bindings and not variables. @yuyichao has been answering this question for years. If they give a reference (maybe to a post of them), I will always link it whenever I see a variation of this question.

1 Like