Don't use Map functions on structs
While it may seem like a good idea, Map
functions should not be used on Elixir structs, as they can lead to some violations of the data structure. Specifically, you can use the Map
API to add keys that don’t exist on the struct.
defmodule Test do
defstruct [:foo]
end
test = %Test{}
# Adds a field :bar that doesn't exist on the struct
%{__struct__: Test, bar: :a, foo: nil} = Map.put(test, :bar, :a)
Instead, use the Map update syntax that validates that you’re using an existing key. If it doesn’t exist, it will throw a KeyError
%{test | bar: :a}
** (KeyError) key :bar not found in: %Test{foo: nil}
(stdlib 3.12.1) :maps.update(:bar, :a, %Test{foo: nil})
(stdlib 3.12.1) erl_eval.erl:256: anonymous fn/2 in :erl_eval.expr/5
(stdlib 3.12.1) lists.erl:1263: :lists.foldl/3
Tweet