Maps
| Map literals | |
| Read with dot and brackets | |
| Update with %{m | k: v} | |
| Keys and values |
Map literals
A map stores labeled values inside percent braces.
Atom keys use the short colon form, while any other key uses the arrow form.
The two styles can mix in one map, and map_size counts the entries.
user = %{name: "Ada", age: 36}
scores = %{"ada" => 10}
map_size(user)
Read with dot and brackets
Dot access reads an atom key and is tight to write.
Bracket access takes any key and answers nil for a missing one.
Dot access raises when the key is absent, so brackets fit optional data.
user = %{name: "Ada", age: 36}
user.name
user[:age]
user[:missing]
Update with %{m | k: v}
The pipe update builds a copy with new values for keys that already exist.
Trying a missing key raises at once, which guards against typos in key names.
Map put adds fresh keys when the shape is allowed to grow.
user = %{name: "Ada", age: 36}
older = %{user | age: 37}
Map.put(user, :city, "Berlin")
Keys and values
Map keys lists every key and Map values lists every value, both as plain lists.
Membership checks fit has_key, which answers true or false for one key.
These three calls cover most questions maps ever get.
user = %{name: "Ada", age: 36}
Map.keys(user)
Map.values(user)
Map.has_key?(user, :name)
Next: Keyword lists
Article author: Arthur Isaev