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 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...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Ada