Maps in Elixir
Set key/value pairs using typical map[key] = value
syntax.
Printing a map with e.g. IO.inspect
will show all of its key/value pairs.
Get a value for a key with map[key]
.
If the key doesn’t exist, Map.get/3
can return a default value.
The built-in map_size
returns the number of key/value pairs when called on a map.
The built-in Map.delete
removes key/value pairs from a map.
To remove all key/value pairs from a map, you can reinitialize it to an empty map.
The optional third return value when getting a value from a map can be used to disambiguate between missing keys and keys with zero values like 0
or ""
. Here we didn’t need the value itself, so we ignored it with the underscore _
.
You can also declare and initialize a new map in the same line with this syntax.
The Map
module contains a number of useful utility functions for maps.
Note that maps appear in the form %{"key" => "value"}
when printed with IO.inspect
.
Next example: Functions.