Search code examples
syntaxerlangrecorderlang-shell

Erlang gives syntax error on record construction


I have the following code in a module:

-module(my_server).

-record(server_opts,
        {port, ip = "127.0.0.1", max_connections = 10}).

Opts1 = #server_opts{port=80}.

When I try to compile it in Erlang shell it gives an error like syntax error before Opts1. Any idea what could be the problem with the code above. Please note that the code is taken from the following website: Record example in Erlang.


Solution

  • The following line:

    Opts1 = #server_opts{port=80}.
    

    Should be contained within a function body:

    foo() ->
        Opts1 = #server_opts{port=80},
        ...
    

    Remember to export the function, so that you can call it from outside the module:

    -export([test_records/0]).
    

    A complete example follows:

    -module(my_server).
    
    -export([test_records/0]).
    
    -record(server_opts, {port,
                          ip = "127.0.0.1",
                          max_connections = 10}).
    
    test_records() ->
        Opts1 = #server_opts{port=80},
        Opts1#server_opts.port.