@@ -26,8 +26,8 @@ defmodule Map do
26
26
%{:a => 1, :b => 2, "hello" => "world"}
27
27
28
28
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:
31
31
32
32
iex> map = %{a: 1, b: 2}
33
33
iex> Map.fetch(map, :a)
@@ -37,18 +37,23 @@ defmodule Map do
37
37
iex> map["non_existing_key"]
38
38
nil
39
39
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`.
44
43
45
44
iex> map = %{foo: "bar", baz: "bong"}
46
45
iex> map.foo
47
46
"bar"
48
47
iex> map.non_existing_key
49
48
** (KeyError) key :non_existing_key not found in: %{baz: "bong", foo: "bar"}
50
49
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
52
57
pattern match, it will match if the map on the right-hand side contains the
53
58
keys on the left-hand side and their values match the ones on the left-hand
54
59
side. This means that an empty map matches every map.
0 commit comments