Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 48 ยท Core Language

Maps and Structs

Learn Elixir maps and structs: building them, reading with dot and bracket syntax, update syntax, nested data, defstruct and @enforce_keys.

When you need to look something up by name, you reach for a map. Maps are Elixir's key-value data structure and show up everywhere: decoded JSON, function options, application state, database rows. A struct is a map with a fixed set of known fields and a name, which gives you compile-time checks and a clear definition of what a piece of data looks like.

This lesson covers building maps, reading and updating them, working with nested data, and then defining structs. Remember that maps are immutable (Immutability and Rebinding): every update returns a new map. The examples are read-only Elixir, plus JavaScript stand-ins where marked. The stand-ins imitate the rules; they are not real Elixir.

Creating maps

A map is written %{key => value}. Keys can be any term. When all keys are atoms there is a shorter syntax:

ELIXIR
scores = %{"ana" => 90, "ben" => 75}
user = %{name: "Ana", age: 30}

user == %{:name => "Ana", :age => 30}   # true, the same map
map_size(user)                          # 2

Every key appears once, and a later duplicate replaces the earlier one. Do not rely on any particular order when you print or iterate a map; it is not insertion order.

Reading values

There are several ways to read, and they differ when the key is missing:

ELIXIR
user = %{name: "Ana", age: 30}

user.name              # "Ana", only for atom keys, raises KeyError if missing
user[:name]            # "Ana", returns nil if missing
user[:email]           # nil
Map.get(user, :email, "n/a")   # "n/a", with a default
Map.fetch(user, :name)         # {:ok, "Ana"}
Map.fetch(user, :email)        # :error
Map.fetch!(user, :email)       # raises KeyError

Use the dot form (user.name) when the key must exist: a typo then fails loudly instead of quietly giving nil. Use user[:name] or Map.get/3 when absence is normal. For string keys you must use the bracket form or Map.get/2, since . only works with atoms.

You can also take maps apart with pattern matching, which only needs to name the keys you care about:

ELIXIR
%{name: name} = %{name: "Ana", age: 30}
name   # "Ana"

Updating maps

ELIXIR
user = %{name: "Ana", age: 30}

Map.put(user, :email, "[email protected]")   # adds or replaces a key
Map.delete(user, :age)                     # %{name: "Ana"}
Map.merge(user, %{age: 31, city: "Oslo"})  # right side wins on conflicts
%{user | age: 31}                          # update syntax

The update syntax %{map | key: value} is special: it only changes keys that already exist, and raises a KeyError otherwise. That makes it great for catching typos, and also a little stricter than Map.put/3. Both leave the original untouched, so remember to bind the result.

Nested data

Real data is often nested. The Access helpers read and update deep values without a pile of intermediate variables:

ELIXIR
state = %{user: %{name: "Ana", address: %{city: "Oslo"}}}

get_in(state, [:user, :address, :city])          # "Oslo"
put_in(state, [:user, :address, :city], "Rome")  # a new nested map
update_in(state, [:user, :name], &String.upcase/1)
state.user.address.city                          # "Oslo", chained dots

With atom keys you can also write put_in(state.user.address.city, "Rome"). Each of these builds a new outer map but shares everything that did not change.

Structs

A struct is defined inside a module with defstruct and gives a map a name and a fixed list of fields:

ELIXIR
defmodule User do
  defstruct [:name, :email, age: 0]
end

ana = %User{name: "Ana"}
# %User{name: "Ana", email: nil, age: 0}

ana.name               # "Ana"
%User{ana | age: 31}   # %User{name: "Ana", email: nil, age: 31}

Fields in the list get nil unless you give a default (age: 0). Key rules:

  • Only the declared fields are allowed. %User{nickname: "x"} fails at compile time.
  • A struct is really a map with a hidden __struct__: User key, so is_map(ana) is true, but structs do not implement the bracket Access syntax: ana[:name] raises. Use ana.name.
  • Pattern matching on the struct name checks the type: %User{name: n} = ana works and fails for other structs or plain maps.
  • The update syntax works and refuses unknown fields.

Required fields with @enforce_keys

@enforce_keys lists fields that must be given when the struct is built:

ELIXIR
defmodule Account do
  @enforce_keys [:owner]
  defstruct [:owner, balance: 0]
end

%Account{owner: "Ana"}   # ok
%Account{}               # ** (ArgumentError) the following keys must also be given when building struct Account: [:owner]

The attribute must appear before defstruct. It only guards creation with %Account{...}. It does not stop someone from later setting the field to nil with the update syntax, so it is a safety net, not full validation.

When to use which

Map, keyword list or struct?

Map Dynamic keys, lookups by name.
Keyword list Short option lists, may repeat keys.
Struct Known fields and a clear type.

Reach for a struct once the shape of the data is settled.

1 / 2

A JavaScript stand-in

First, a stand-in for the update syntax and @enforce_keys. It uses plain objects, so it only models the rules: update must use an existing key, and required keys must be present when building.

JS Update syntax and enforce_keys (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Now nested data. This stand-in implements get_in and put_in for a list of keys and shows that unchanged branches are shared.

JS get_in and put_in (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does %{name: "Ana"}[:email] return?

    Bracket access returns nil for a missing key. The dot form (map.email) would raise a KeyError instead.
  2. 2. What happens with %{user | email: "[email protected]"} when user has no :email key?

    The update syntax only changes existing keys. Use Map.put/3 to add a new key.
  3. 3. What does @enforce_keys [:owner] do?

    It raises an ArgumentError if the key is missing when the struct is built. It does not validate values or block later updates.
  4. 4. How do you read the name field of a struct ana?

    Structs do not support bracket Access, but ana.name works because the field is an atom key.

Summary

  • Maps are key-value pairs written %{key => value}; atom keys can use the shorter %{name: "Ana"} form.
  • map.key raises when missing, map[:key] returns nil, Map.fetch/2 returns a tagged result.
  • %{map | key: value} updates only existing keys; Map.put/3 adds or replaces.
  • get_in, put_in and update_in handle nested data.
  • Structs are maps with a name and fixed fields declared by defstruct; @enforce_keys requires fields at creation.
  • Everything returns new data; bind the result.

Next up: Conditionals: if, unless, cond and case.