Records
| Define a record | |
| Create one | |
| Read fields | |
| Update fields |
Define a record
A record is a tuple with named positions. Define it at the top of the module with the record attribute, listing the field names in order.
The compiler turns record syntax into plain tuple access, so records cost nothing at runtime.
-record(person, {name, age}).
% the tuple behind the scenes: {person, Name, Age}
Create one
The hash and record name build a record. Every field can take a value, and any field left out gets the atom undefined as its default.
Set only the fields you care about, and let the defaults fill the rest.
1> P = #person{name = "Ada", age = 36}.
{person,"Ada",36}
2> #person{name = "Grace"}.
{person,"Grace",undefined}
Read fields
The dot syntax reads one field from a record. It is shorthand for element at the field position, with the tag checked for you.
The compiler raises a badarg error when the value is not the record you expect, which catches mix-ups early.
1> P = #person{name = "Ada", age = 36}.
2> P#person.name.
"Ada"
3> P#person.age.
36
Update fields
The record expression with new values returns a fresh record with those fields replaced. The original stays untouched, as single assignment demands.
Update one field or many in the same expression, and chain the result straight into the next call.
1> P#person{age = 37}.
{person,"Ada",37}
2> Older = P#person{age = P#person.age + 1}.
{person,"Ada",37}
Next: Exceptions: try and catch
Article author: Arthur Isaev