Maps and Nested Data Structures
Maps
Maps in Elixir are key-value stores. Maps can be created by using the %{}
, Keys in a map can be of any type. The map data-structures are similar to keyword lists except they are unordered.
Try typing the following examples.
map = %{:msg => "Hello", "receiver" => :world}
map[:msg]
map["msg"]
map[:"msg"]
map["receiver"]
name = "Foo"
map = %{name => "world"}
map[name]
Nested data structures
Elixir provides a way for us to hold variables inside of maps. For instance, we can create a list of users that is a key-value map to another nested map:
iex> users = [
john: %{name: "John", age: 27, languages: ["Erlang", "Ruby", "Elixir"]},
mary: %{name: "Mary", age: 29, languages: ["Elixir", "F#", "Clojure"]}
]
We can then get variables using the []
and .
syntax:
iex> users[:john].age # 27
We can then manipulate maps like so -
map = %{:msg => "Hello", "receiver" => :world}
%{map | msg: "goodbye"}
map.msg
Check out the Kernel module documentation for more information on other functions available to use when using nested data structures.
Next step:
Go on to Pipe operator.
Or:
Go back to Keyword Lists.