by Example

Records


A record in Erlang is similar to a struct in C.
It is typically used for storing a fixed number of elements.
Record expressions are translated to tuple expressions
during compilation.



To define a record use the `-record` directive.



Fields can have default values



When expanded to a tuple the `person` record
would look something like this:
{person, NameValue, AgeValue ... StatusValue}


You can access a record's fields using the dot notation

To inspect a record call the function `record_info/2`.

Note that the size is "number of fields" + 1.




-module (records).
-compile([export_all]).


-record(person, {
        name,
        age,

        status = single
    }).




run() ->
    P1 = #person{name="Joe Doe", age="25"},

    io:format("Created person ~p~n", [P1#person.name]),

    io:format("Record fields: ~p~n", [record_info(fields, person)]),

    io:format("Record size: ~p~n", [record_info(size, person)]).
1> c(records).
{ok,records}

2> records:run().
Created person "Joe Doe"
Record fields: [name,age,status]
Record size: 4
ok


Next: Guards