Nested access

In Elixir, real data is nested: a company has an owner, the owner has an address, the address has a city. Reading a field several levels down is a chain of dots, and changing one is put_in/2 or update_in/2, which rebuild the outer values on the way back. This lesson puts a struct inside a struct and follows the chain with the calls the standard library provides.

A struct in a struct

A field may hold another struct, and the dot chain reads it one level at a time. The script defines the two modules, builds a company with an owner, and changes the age through the chain:

nested.exs

defmodule User do defstruct name: "guest", age: 0 end defmodule Company do defstruct name: "", owner: nil end owner = struct(User, %{name: "Ada", age: 36}) company = struct(Company, %{name: "ACME", owner: owner}) IO.puts(company.owner.name) older = put_in(company.owner.age, 37) IO.inspect(older.owner.age) IO.inspect(company.owner.age)

elixir nested.exs

Ada
37
36

company.owner.name reads through two structs. The put_in/2 call returns a second company with a second owner, and the last line proves that the first company still has age 36: the change happened on a copy of the path, not in the data. This is the same immutability rule as every other value, applied one level deeper.

put_in and update_in

put_in/2 replaces the value at the path, and update_in/2 applies a function to it. Both take the path in the dot form, both return the whole structure, and both leave the original untouched:

update.exs

defmodule User do defstruct name: "guest", age: 0 end defmodule Company do defstruct name: "", owner: nil end owner = struct(User, %{name: "Ada", age: 36}) company = struct(Company, %{name: "ACME", owner: owner}) older = update_in(company.owner.age, &(&1 + 1)) IO.inspect(older.owner.age) IO.inspect(company.owner.age)

elixir update.exs

37
36

The function receives the old value and returns the new one, which is the shape a counter, a timestamp or a list append needs. The path is written with dots because the values are structs; a plain map takes the same calls with the same dot syntax, and a path that starts from a variable works too.

get_in over plain maps

get_in/2 reads a path given as a list of keys instead of a chain of dots, and it is the call for plain maps and keyword lists. The keys are looked up with the Access protocol, so a string key and an atom key are different paths:

plain.exs

company = %{name: "ACME", owner: %{name: "Ada", age: 36}} IO.puts(get_in(company, [:owner, :name])) IO.inspect(put_in(company.owner.age, 37))

elixir plain.exs

Ada
%{name: "ACME", owner: %{name: "Ada", age: 37}}

A path may also name a struct field through Access.key!/1, which is how a dynamic path reaches a struct: get_in(company, [Access.key!(:owner), Access.key!(:name)]). The next section shows why the plain path fails on a struct.

The mistake: get_in on a struct

A struct is not a map for the Access protocol. get_in/2 with atom keys asks the struct for a field through the protocol, and a struct that does not implement Access stops the program:

access.exs

defmodule User do defstruct name: "guest", age: 0 end defmodule Company do defstruct name: "", owner: nil end owner = struct(User, %{name: "Ada"}) company = struct(Company, %{name: "ACME", owner: owner}) IO.puts(get_in(company, [:owner, :name]))

elixir access.exs

** (UndefinedFunctionError) function Company.fetch/2 is undefined (Company does not implement the Access behaviour

You can use the "struct.field" syntax to access struct fields. You can also use Access.key!/1 to access struct fields dynamically inside get_in/put_in/update_in). Make sure the module name is correct and has been specified in full (or that an alias has been defined)
    Company.fetch(%Company{name: "ACME", owner: %User{name: "Ada", age: 0}}, :owner)
    (elixir 1.19.7) lib/access.ex:326: Access.get/3
    (elixir 1.19.7) lib/kernel.ex:2925: Kernel.get_in/2
    access.exs:12: (file)

The message names the fix: the dot syntax for struct fields, or Access.key!/1 inside a dynamic path. The error is a reminder that a struct is a map with a type, and the protocol that reads maps by key does not automatically read its fields. The message is one long sentence with its own parentheses, and it is shown as the runtime prints it.

The mistake: a field that is not there

A dot access on a struct field that the struct does not declare raises KeyError, and the report shows the value it looked in. The field list of the struct is the answer:

missing.exs

defmodule User do defstruct name: "guest", age: 0 end user = struct(User, %{name: "Ada"}) IO.puts(user.email)

elixir missing.exs

** (KeyError) key :email not found in:

    %User{name: "Ada", age: 0}

    missing.exs:6: (file)
    (elixir 1.19.7) lib/code.ex:1613: Code.require_file/2

The output shows the two fields the struct has, so the missing one is easy to spot. A field added to the struct later is the fix, or Map.get(user, :email) when a missing value should return nil instead of raising. The structs lesson shows the declaration and the enforced keys.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does put_in(company.owner.age, 37) return?

    Answer

    A new company with a new owner whose age is 37

    The call rebuilds the path and returns the whole outer structure.

  2. What is the difference between put_in/2 and update_in/2?

    Answer

    put_in takes the new value, update_in takes a function of the old one

    Both rebuild the structure; the second computes the value from the old one.

  3. Which call reads a path of keys from a plain map?

    Answer

    get_in/2 with a list of keys

    get_in/2 takes the data and the list of keys to follow.

  4. Why does get_in(company, [:owner, :name]) fail on a struct?

    Answer

    A struct does not implement the Access protocol

    Access reads maps by key; struct fields are reached with dots or Access.key!/1.

  5. What does this program print? company = %{owner: %{age: 36}} older = put_in(company.owner.age, 37) IO.inspect(older)

    Answer

    %{owner: %{age: 37}}

    put_in returns the whole map with the new value in place.

  6. What does this program print? company = %{owner: %{age: 36}} IO.inspect(update_in(company.owner.age, &(&1 + 1)))

    Answer

    %{owner: %{age: 37}}

    update_in applies the function and returns the rebuilt map.

  7. What does this program print? company = %{owner: %{name: "Ada"}} IO.puts(get_in(company, [:owner, :name]))

    Answer

    Ada

    get_in follows the two keys and IO.puts/1 prints the binary without quotes.

  8. What does this program do? defmodule User do defstruct name: "guest", age: 0 end user = struct(User, %{name: "Ada"}) IO.puts(user.email)

    Answer

    A KeyError, because the struct has no email field

    A dot access on a field the struct does not declare raises at run time.

  9. Why does get_in(company, [:name]) fail when company is a struct?

    Answer

    An UndefinedFunctionError, because Company does not implement the Access behaviour

    The plain key path needs Access, which a struct does not implement until it says so.

  10. What does update_in(company.owner.age, &(&1 + 1)) leave in the original company?

    Answer

    The old age, because the call builds a new structure

    Values are immutable; the call returns a new structure and the original is unchanged.

Article author: Arthur Isaev