Updating Map with "shortcut syntax"

I often see the “shortcut syntax” for updating maps / replacing values using pipe character being advocated. Something like:

iex(19)> %{ %{a: 0, b: 1, c: 2, d: 3} | c: 3, d: 4}
%{a: 0, b: 1, c: 3, d: 4} 

OTOH I vaguely recall reading somewhere about this being not a thing to rely on due to … <and here I forgot the explanations and can’t find where I read them>

Documentation mentions this syntax, however: " Maps also support a specific update syntax to update the value stored under existing atom keys:", so… are/were there any caveats/gotchas in using the pipe for updating values of existing keys?

Shortcut syntax is particularly concise when dealing with structs since they fulfil the two preconditions definitively: (a) atom keys and (b) keys are known to exist.

They are less useful with dealing with arbitrary maps because one or both of the preconditions for using shortcut syntax can’t be assumed.

1 Like

syntax to update the value stored under existing atom keys

It’s interesting the documentation calls out atom keys specifically. You can also use it to update non-atom keys (though the syntax is slightly different, I suppose):

iex(1)> my_map = %{"a" => 3, "b" => 4}
%{"a" => 3, "b" => 4}
iex(2)> %{my_map | "b" => 5}
%{"a" => 3, "b" => 5}