Structs in Elixir

In Elixir, a struct is a map with a fixed set of keys and the name of a module attached to it. The module declares the fields with defstruct, each with a default, and every value built from it carries that shape: an unknown key is refused when the value is built, not found missing later. This is the data type a program uses for a user, an order or a message, and the nested access lesson puts one inside another.

defstruct gives a shape

defstruct lists the fields with their defaults. A field without a default is written as a bare atom and starts as nil. The module also shows the other half of the type: a function that matches on the struct in its head:

user.ex

defmodule User do defstruct name: "guest", age: 0 def greet(%User{name: name}), do: "hello #{name}" end

The pattern %User{name: name} matches only a value of this struct and binds its name; a plain map or another struct fails the match. That check is what makes a struct a type rather than a convention: the module name is part of every value, so a function can accept exactly this shape.

Build a struct

A struct literal is a percent sign, the module name and the fields to set: %User{name: "Ada", age: 36}. Missing fields take their defaults. A struct literal is expanded when the file is compiled, so the module has to be compiled first: the two commands below compile the module file and then run the script that uses it:

elixirc user.ex

build.exs

user = %User{name: "Ada", age: 36} older = %{user | age: 37} IO.inspect(user) IO.inspect(older) IO.puts(User.greet(user))

elixir build.exs

%User{name: "Ada", age: 36}
%User{name: "Ada", age: 37}
hello Ada

The printed value shows the module name, which is how a struct differs in the output from a plain map. Inside the same script a struct literal cannot be used, because the module is defined in that very file and is not compiled yet; the language says so with a compile error. A script that defines its own struct builds values with struct(User, %{name: "Ada"}), which reads the fields at run time and produces the same value.

Update and share

A struct is immutable, so an update builds a second value that shares everything the first one does not change. The update syntax names the new fields after the vertical bar, and the old value stays exactly as it was:

The second line of build.exs is the update, and its output shows the two values side by side: the first keeps age 36 and the second has 37. The update keeps the module name and every field it does not name, which is why a program describes a change without a setter and without copying the fields by hand.

Enforce a key

Some fields have no sensible default, such as the id of a database row. @enforce_keys lists the fields every build must provide. A struct literal without one fails at compile time, and struct!/2, which builds at run time, fails the same way:

enforce.exs

defmodule Account do @enforce_keys [:id] defstruct [:id, balance: 0] end IO.inspect(struct!(Account, %{id: 7})) IO.inspect(struct!(Account, %{balance: 10}))

elixir enforce.exs

%Account{id: 7, balance: 0}
** (ArgumentError) the following keys must also be given when building struct Account: [:id]
Account.__struct__/1
(elixir 1.19.7) lib/kernel.ex:2549: Kernel.struct!/2
enforce.exs:7: (file)

The first value is complete and the second is refused before it exists. A plain struct/2 does not enforce the keys, which is why the lesson uses the bang version: it is the run-time form of the check that %Account{} makes when the file is compiled.

The mistake: updating a missing key

The update syntax replaces a key that already exists and never adds one. A map without the key stops the program with a KeyError, and the message names the key it could not find:

missingkey.exs

user = %{name: "Ada"} IO.inspect(%{user | age: 37})

elixir missingkey.exs

** (KeyError) key :age not found
missingkey.exs:2: (file)
(elixir 1.19.7) lib/code.ex:1613: Code.require_file/2

The fix is Map.put(user, :age, 37), which adds a key, or a struct that declares age from the start. The distinction is useful: an update says "this key must already be here", and a program that means "add it" should say so with the call that adds.

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 is a struct in Elixir?

    Answer

    A map with a fixed set of fields and the name of a module

    A struct is a map whose keys are declared and whose value carries its module name.

  2. What happens when a struct literal names a field that defstruct does not declare?

    Answer

    The build fails, because the struct has a fixed set of fields

    The struct shape is fixed at compile time, so an unknown field is an error.

  3. What does the update syntax %{user | age: 37} need?

    Answer

    The key age must already exist

    An update replaces existing keys; adding a key is Map.put/3.

  4. What does @enforce_keys do?

    Answer

    It requires the listed fields when the struct is built

    A build without an enforced key is refused rather than filled with nil.

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

    Answer

    Ada

    struct/2 fills the fields it is given, and the name is printed.

  6. What does this program print? defmodule User do defstruct name: "guest", age: 0 end IO.inspect(struct(User, %{}))

    Answer

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

    The defaults fill both fields, and inspect shows the struct with its module name.

  7. What does this program print? defmodule User do defstruct name: "guest", age: 0 end user = struct(User, %{name: "Ada", age: 36}) older = %{user | age: 37} IO.puts(older.age)

    Answer

    37

    The update changes the age in a second struct, and the new value is printed.

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

    Answer

    true

    A struct is a map, so is_map/1 is true for it.

  9. What does this program do? defmodule Account do @enforce_keys [:id] defstruct [:id, balance: 0] end IO.inspect(struct!(Account, %{balance: 10}))

    Answer

    An ArgumentError: the id key must also be given

    @enforce_keys makes the build refuse a struct that lacks the enforced field.

  10. What does this program do? user = %{name: "Ada"} IO.inspect(%{user | age: 37})

    Answer

    A KeyError, because the map has no age key

    The update syntax replaces existing keys only, so a missing key raises.

Автор статьи: Arthur Isaev