Allyl Isocyanate
Allyl Isocyanate

Reputation: 13616

Defining Erlang record in a module

I can define a record on the erl shell via:

129> rd(person, {name=""}).
person
130> #person {}.
#person{name = []}
131> #person {name="dummy"}.
#person{name = "dummy"}

But I'm not sure how to define and use records in a module. When I create my_module.erl:

-module(my_module).

-record(person, {name, phone, address}).

#person {name="dummy"}.

...and try to compile, I get:

132> c(my_module).          
my_module.erl:5: syntax error before: '#'
my_module.erl:3: Warning: record person is unused
error

The documentation says rd is used in the shell since records are available at compile time, not runtime. So I would assume I wouldn't need to use rd in the module definition.

Upvotes: 0

Views: 1288

Answers (2)

rausch
rausch

Reputation: 3388

If you want to use a record in multiple modules, you can put it in a header file (e.g. foo.hrl):

-record(foo, {bar, baz}).

You can then include the header file in the modules you need it in:

-include_lib("path/to/foo.hrl")

Usually these header files are being put into the include directory of your application.

Edit: I quote from the documentation:

include_lib is similar to include, but should not point out an absolute file. Instead, the first path component (possibly after variable substitution) is assumed to be the name of an application. Example:

-include_lib("kernel/include/file.hrl").

So, it seems what I wrote is actually more true for include.

Upvotes: 5

chops
chops

Reputation: 2612

You have defined it right, but a record can only be used inside a function (when it's inside a module).

So add something like

test_record() -> #person{name="dummy"}.

Then you can see the results from the Erlang shell with

my_module:test_record()

Upvotes: 4

Related Questions