Skip to content

Commit 4e3e9ce

Browse files
authored
Clarify the dual access syntax for maps and mention structs
1 parent 239def6 commit 4e3e9ce

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

lib/elixir/lib/map.ex

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ defmodule Map do
2626
%{:a => 1, :b => 2, "hello" => "world"}
2727
2828
Keys in maps can be accessed through some of the functions in this module
29-
(such as `Map.get/3` or `Map.fetch/2`) or through the `[]` syntax provided by
30-
the `Access` module:
29+
(such as `Map.get/3` or `Map.fetch/2`) or through the `map[]` syntax provided
30+
by the `Access` module:
3131
3232
iex> map = %{a: 1, b: 2}
3333
iex> Map.fetch(map, :a)
@@ -37,18 +37,23 @@ defmodule Map do
3737
iex> map["non_existing_key"]
3838
nil
3939
40-
The alternative access syntax `map.key` is provided alongside `[]` when the
41-
map has a `:key` key; note that while `map[key]` will return `nil` if `map`
42-
doesn't contain `key`, `map.key` will raise if `map` doesn't contain
43-
the key `:key`.
40+
For accessing atom keys, one may also `map.key`. Note that while `map[key]` will
41+
return `nil` if `map` doesn't contain `key`, `map.key` will raise if `map` doesn't
42+
contain the key `:key`.
4443
4544
iex> map = %{foo: "bar", baz: "bong"}
4645
iex> map.foo
4746
"bar"
4847
iex> map.non_existing_key
4948
** (KeyError) key :non_existing_key not found in: %{baz: "bong", foo: "bar"}
5049
51-
Maps can be pattern matched on; when a map is on the left-hand side of a
50+
The two syntaxes for accessing keys reveal the dual nature of maps. The `map[key]`
51+
syntax is used for dynamically created maps that may have any key, of any type.
52+
`map.key` is used with maps that hold a predetermined set of atoms keys, which are
53+
expected to always be present. Structs, defined via `defstruct/1`, are one example
54+
of such "static maps", where the keys can also be checked during compile time.
55+
56+
Maps can be pattern matched on. When a map is on the left-hand side of a
5257
pattern match, it will match if the map on the right-hand side contains the
5358
keys on the left-hand side and their values match the ones on the left-hand
5459
side. This means that an empty map matches every map.

0 commit comments

Comments
 (0)