Elixir Structs
A struct is a map with a fixed set of keys defined by a module. The module names the fields once, and every struct built from it has exactly those fields.
Build a struct from the defaults
defstruct names the fields and their defaults. struct(Person) builds one with every default in place.
defmodule Person do
defstruct name: "Ana", age: 31
end
person = struct(Person)
IO.inspect(person)
IO.puts(person.name)Override a field at build time
struct/2 overrides the fields named in the second argument. Fields left out keep their defaults.
defmodule Person do
defstruct name: "Ana", age: 31
end
person = struct(Person, name: "Bo")
IO.puts(person.name)
IO.puts(person.age)Two structs share the same fields
Each build starts from the same field list. Only the values differ between the two structs.
defmodule Person do
defstruct name: "Ana", age: 31
end
ana = struct(Person)
bo = struct(Person, name: "Bo", age: 25)
IO.inspect(ana)
IO.inspect(bo)Example
defmodule Person do
defstruct name: "Ana", age: 31
end
person = struct(Person, age: 40)
IO.inspect(person)
IO.puts(person.name)
IO.puts(person.age)
IO.puts(is_map(person))Key points
- defstruct: defstruct inside a module lists the fields and their default values.
- Fixed keys: A struct always has the same set of keys, unlike a plain map where keys can be added freely.
- struct/1: struct(Person) builds a struct filled with the default values.
- struct/2: struct(Person, name: "Bo") builds a struct and overrides the named fields.
- Field access: person.name reads a field with dot syntax, just like a map with atom keys.
In this example, the Person module defines the name and age fields with defaults. struct/2 overrides only the age, dot syntax reads both fields back, and is_map confirms a struct is a map.
Note
A struct is still a map underneath, with its module name stored alongside the fields.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
With defstruct name: "Ana", age: 31 in module Person, what is struct(Person, name: "Bo").age?