Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Erlang records


May 13, 2021 Erlang


Table of contents


Erlang records

Records are defined as follows:

-record(name_of_record,{field_name1, field_name2, field_name3, ......}).

For example

-record(message_to,{to_name, message}).

This is equivalent to:

{message_to, To_Name, Message}

Use an example to illustrate how to create a record:

#message_to{message="hello", to_name=fred)

The code above creates the following record:

{message_to, fred, "hello"}

Note that when you create records this way, you don't need to consider the order in which each section is assigned a value. A nother advantage of this is that you can define the interfaces in the header file, which makes it very easy to modify the interfaces. F or example, if you want to add a new domain to a record, you only need to modify it where you use it, not where you use the record. I f you miss some of these fields when you create records, they get a default atomic value of undefined.

Using records for pattern matching is the same as creating records. F or example, in the case of receive:

#message_to{to_name=ToName, message=Message} ->

This is the same as the following code:

{message_to, ToName, Message}