Erlang basics · Lesson 21 (open contents)
Keep records behind a module boundary
Use a record internally and return a public map to callers.
Run this first
Run it once, change one input, and compare the new result.
%% Keep this record inside its owning module
-record(user, {name, age = 0}).
public(#user{name = Name, age = Age}) ->
#{name => Name, age => Age}.- Calling
public/1inside the module returns a map such as#{name => <<"Maya">>,age => 12}.
Read from the first line down
- Read
#user{}: Construct or match the private record. - Read
Record#user.name: Read one record field. - Read
#{key => value}: Return a public map.
Symbols are not secret signs
#user{}Construct or match the private record.
Record#user.nameRead one record field.
#{key => value}Return a public map.
Match each name to its meaning
record
A record gives compile-time names to tuple positions inside modules that share its definition.
public boundary
A public boundary is the data shape other modules are allowed to depend on.
conversion
Converting a private record to a map prevents callers from depending on tuple layout.
Why these forms are useful
Run the example first. Predict one result, then change one input and run it again.
A record gives compile-time names to tuple positions inside modules that share its definition.
A public boundary is the data shape other modules are allowed to depend on.
Close the answer and try
Hide age and expose only the name.
public(#user{name = Name}) -> #{____ => Name}.Target result: Return a map with the name key.
Stuck? Read one hint
Use the atom name.
After you run it, see one answer
public(#user{name = Name}) -> #{name => Name}.Think about it: Why not return a record from a public API?
Records compile to tuples, so changing a field can silently change the tuple layout expected by callers.
Remember these three lines
- 1
Treat records as private structure.
- 2
Use stable public data shapes.
- 3
Convert at module boundaries.