Records
A record such as %{name: String, age: Integer} needs no declaration. It
emits a BEAM map with atom keys. The field set is exact: extra fields are a
different record type. A record is accepted as Map<K, V> when its atom keys
and field values fit K and V. Build a smaller record by writing the fields
you want.
%{name: String, age: Integer} describes a record with exactly two fields.
The type is written inline and needs no declaration or module import.
Records are structural, not nominal: two functions in different modules that
ask for the same shape accept the same values.
Exact by design
Section titled “Exact by design”Write the fields, read them with .field, update with %{value | field: ...}:
mod records
pub fn birthday(user: %{name: String, age: Integer}) -> %{name: String, age: Integer} { %{user | age: user.age + 1}}
pub fn origin() -> %{x: Integer, y: Integer} { %{x: 0, y: 0}}
pub fn name_of(user: %{name: String, age: Integer}) -> %{name: String} { %{name: user.name}}Record types have no width subtyping. A literal with an extra field has a different type.
Projection is explicit: name_of builds the smaller record by
writing the fields it wants. Neither the compiler nor the runtime will
silently drop or invent fields. When you need a field set that changes at
runtime, that’s a Map<K, V>, not a record. A dictionary cannot become
an exact record by assignment.
Destructuring
Section titled “Destructuring”Because the argument’s type already fixes the shape, destructuring in a binding cannot fail:
mod records
@doc "An exact record can be destructured in an infallible binding."pub fn coordinates(point: %{x: Integer, y: Integer}) -> {Integer, Integer} { %{x: x, y: y} = point {x, y}}In patterns, record matching has its own rules, separate from map patterns:
%{name: name} requires that field without pinning the exact key set, and
%{} matches any map. Reach for those in matching when a
value may be one of several shapes.
Updates keep the shape
Section titled “Updates keep the shape”%{user | age: ...} replaces an existing field while preserving the record’s
type. Map operations return dictionaries; they do not establish a new exact
record shape. To return a different record shape, construct it explicitly.