Reading — step 1 of 5
Learn
Erlang has two main structured-data options: records (older) and maps (modern, since R17).
Records are sugar for tagged tuples:
-record(person, {name, age, email}).
P = #person{name="Ada", age=36, email="[email protected]"},
P#person.name, %% access
P2 = P#person{age=37}, %% update
Under the hood, P is the tuple {person, "Ada", 36, "[email protected]"}. The record syntax is just compile-time sugar.
Records have a fixed shape — once defined, you can't add fields without recompiling. They're fast and well-known but rigid.
Maps (#{...}) are dynamic key-value:
P = #{name => "Ada", age => 36, email => "[email protected]"},
maps:get(name, P), %% "Ada"
maps:get(role, P, undefined), %% default if missing
P2 = P#{age => 37}, %% update / add
maps:remove(email, P), %% remove key
maps:keys(P), %% list of keys
Pattern match on maps:
#{name := Name, age := Age} = P,
%% Name="Ada", Age=36
The := is the match-existing-key operator. Maps without that key would not match.
Maps vs records — when to use:
- Records — fixed-schema data, performance-sensitive, cross-module APIs
- Maps — dynamic data, JSON-like structures, optional fields, configuration
Most new Erlang code prefers maps for flexibility. Records still appear heavily in older codebases and OTP itself.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…