Hello, I’m new to Elixir, I’m reading a book called Learning Functional Programming with Elixir I’m reading a subject of how Elixir data are immutable but when I just create a value in iex shell (Elixir (1.11.0) ) like this:
message = "Hello, World!!!"
display the above variable I get what I’m expecting but what I do not understand is, if I mutate the message variable there’s not an error.
message = "Hello!!!"
displaying again message variable I get no error and the output is Hello!!!
Please help me to understand what immutability means and how it works in Elixir
It can be slightly confusing because elixir allows rebinding identifiers. Immutability is as a result a bit closer to how strings behave in many popular languages (e.g. C#) where the value a variable name points to can change but the value itself cannot.
Every change to a value results in a new value and to keep track of it you need to bind it to a name, but the name can be reused while the value itself can’t be changed.
If you consider this JavaScript example:
let person = { name: “Bob” };
Then following this in elixir you could do something conceptually similar to:
person = { name: “Nicola” };
But you couldn’t do something conceptually similar to:
person.name = “Nicola”;
However another slight difference in this comparison is in elixir everything is passed by value, nothing is passed by reference so changes to what a name points to only impacts usage of that name going forward and never any previous usage of that name.