Elixir Structs
A struct is a map with a fixed set of fields, default values and a name. Structs give your data a clear shape: the compiler checks field names, and functions can pattern match on the struct type. They are defined inside a module with defstruct, and the struct takes the module's name.
defmodule Book do
defstruct title: nil, author: nil, pages: 0, tags: []
end
defmodule Demo do
def run do
book = %Book{title: "Dune", author: "Frank Herbert", pages: 412}
IO.inspect(book)
IO.inspect(book.title)
IO.inspect(book.tags)
empty = %Book{}
IO.inspect(empty.pages)
end
end
Demo.run()%Book{title: "Dune", author: "Frank Herbert", pages: 412, tags: []}
"Dune"
[]
0
%Book{...} creates a struct. Fields you don't give get their defaults.
Note: Why is the code wrapped in a
Demomodule? Struct literals like%Book{}are expanded when the code is compiled. In a script, the top-level code is compiled together with thedefmoduleabove it, beforeBookexists, so%Book{}at the top level of the same file is a compile error ("the struct was not yet defined"). Code inside a later module is compiled afterBookis defined. In a Mix project, where every module lives in its own file, this never comes up.
Compile-time checks
Unknown fields are an error, which catches typos that a plain map would silently accept:
defmodule Point do
defstruct x: 0, y: 0
end
defmodule Demo do
def run do
p = %Point{x: 1, y: 2}
IO.inspect(%{p | y: 10})
IO.inspect(Map.keys(p) |> Enum.sort())
try do
Code.eval_string("%Point{x: 1, z: 3}")
rescue
e in KeyError -> IO.puts(Exception.message(e))
end
end
end
Demo.run()%Point{x: 1, y: 10}
[:__struct__, :x, :y]
key :z not found
Code.eval_string/1 is used only so that the mistake can be shown without stopping the script: written directly in the code, %Point{z: 3} would be a compile error. Notice the hidden __struct__ key: a struct is a map whose __struct__ field holds the module name.
Required fields
@enforce_keys lists fields that must be given when the struct is created:
defmodule User do
@enforce_keys [:email]
defstruct [:email, :name, role: :member]
end
defmodule Demo do
def run do
IO.inspect(%User{email: "kai@example.com"})
try do
Code.eval_string("%User{name: \"Kai\"}")
rescue
e in ArgumentError -> IO.puts(Exception.message(e))
end
end
end
Demo.run()%User{email: "kai@example.com", name: nil, role: :member}
the following keys must also be given when building struct User: [:email]
In defstruct [:email, :name, role: :member], fields listed as plain atoms default to nil.
Structs are maps, but not enumerable
You can read fields with ., update them with %{struct | field: value} and use Map functions. But structs do not implement Access (book[:title]) or Enumerable (Enum.map(book, ...)). That's deliberate: a struct is a single record, not a collection.
defmodule Book do
defstruct title: nil, pages: 0
end
defmodule Demo do
def run do
book = %Book{title: "Kindred", pages: 264}
IO.inspect(Map.get(book, :pages))
IO.inspect(is_map(book))
IO.inspect(is_struct(book, Book))
IO.inspect(Map.from_struct(book))
try do
book[:title]
rescue
e in UndefinedFunctionError -> IO.puts("book[:title] raised #{inspect(e.__struct__)}")
end
end
end
Demo.run()264
true
true
%{title: "Kindred", pages: 264}
book[:title] raised UndefinedFunctionError
Pattern matching on structs
Matching %Book{} in a function head accepts only Book structs, which makes functions precise:
defmodule Shape do
defmodule Circle, do: defstruct([:r])
defmodule Rect, do: defstruct([:w, :h])
def area(%Circle{r: r}), do: Float.round(:math.pi() * r * r, 2)
def area(%Rect{w: w, h: h}), do: w * h
end
defmodule Demo do
alias Shape.{Circle, Rect}
def run do
shapes = [%Circle{r: 1}, %Rect{w: 3, h: 4}, %Circle{r: 2.5}]
IO.inspect(Enum.map(shapes, &Shape.area/1))
# A plain map with the same keys is NOT a Rect
plain = Map.new(w: 3, h: 4)
try do
Shape.area(plain)
rescue
e in FunctionClauseError -> IO.puts(Exception.message(e))
end
end
end
Demo.run()[3.14, 12, 19.63]
no function clause matching in Shape.area/1
Nested defmodule creates Shape.Circle and Shape.Rect; alias Shape.{Circle, Rect} inside Demo shortens both.
Structs with functions
The usual design is: the struct and the functions that work on it live in the same module, with a constructor that validates input:
defmodule Money do
defstruct [:cents, currency: "EUR"]
def new(amount, currency \\ "EUR") when is_number(amount) do
%Money{cents: round(amount * 100), currency: currency}
end
def add(%Money{currency: c} = a, %Money{currency: c} = b), do: %Money{a | cents: a.cents + b.cents}
def add(%Money{}, %Money{}), do: {:error, :currency_mismatch}
def to_string(%Money{cents: cents, currency: c}) do
"#{div(cents, 100)}.#{String.pad_leading(Integer.to_string(rem(cents, 100)), 2, "0")} #{c}"
end
end
total = Money.add(Money.new(12.5), Money.new(7.55))
IO.puts(Money.to_string(total))
IO.inspect(Money.add(Money.new(1), Money.new(1, "USD")))20.05 EUR
{:error, :currency_mismatch}
The first add clause uses the same variable c twice, so it only matches when both currencies are equal.
Test yourself
What happens when you write %Point{z: 1} for a struct without a :z field?
- The key is added
- It is a compile-time error
- It returns nil
- z is ignored
What does @enforce_keys [:email] do?
- Makes email immutable
- Requires
:emailto be given when the struct is built - Validates the email format
- Hides the field
Why does Enum.map(%Book{}, ...) fail?
- Structs are not maps
- Structs don't implement the Enumerable protocol
- Enum only works on lists
- Book has no fields