Maps let us add new key/value entries and update existing entries without traversing the whole structure. But as with all values in Elixir, a map is immutable, and so the result of the update is a new map.
The simplest way to update a map is with this syntax:
| new_map = %{ old_map | key => value, … } |
This creates a new map that is a copy of the old, but the values associated with the keys on the right of the pipe character are updated:
| iex> m = %{ a: 1, b: 2, c: 3 } |
| %{a: 1, b: 2, c: 3} |
| iex> m1 = %{ m | b: "two", c: "three" } |
| %{a: 1, b: "two", c: "three"} |
| iex> m2 = %{ m1 | a: "one" } |
| %{a: "one", b: "two", c: "three"} |
However, this syntax will not add a new key to a map. To do this, you have to use the Map.put_new/3 function.