All lessons

Maps

8 min · Elixir

Store values under named keys with Map.new and map[key].

Elixir · Maps0/5 cleared

Enemy 1 of 5

Creating and reading a map

A map stores values under names called keys, so you can fetch a value by its key instead of by its position in a list.

This code builds a map called player and prints the value stored under the key name. Press Run to see it print Ada.

Why this works

A list is naturally ordered and indexed by position, but plenty of data is more naturally described by name than by position: a player's stats, the fields of a config. Elixir's map type stores key-value pairs and lets you fetch a value directly by its key, without needing to know or care what position it happens to occupy.

`%{key: value, ...}` builds a map literal. The `key:` syntax (with a colon right after the key name) is shorthand for atom keys, which are Elixir's lightweight, named-constant values (similar in spirit to symbols in Ruby, or enum-like constants elsewhere). Reading a value back out uses square-bracket syntax with the key prefixed by a colon: `player[:name]`.

Like every other data structure you've met so far, maps are immutable: nothing about `player` changes once it's created. Looking up a key that isn't present with `map[:missing]` returns `nil` rather than raising an error (unlike Elixir lists, where an out-of-range access does raise). Worth remembering, since a typo'd key name will silently give you `nil` instead of an obvious crash.

You
Pincer Crab
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.