문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

Maybe, you've thought that Opts1 is a global constant, but there are no global variables in erlang.

You may use macro definitions to have something like global constants (which are actually replaced in compile time):

-module(my_server).

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

%% macro definition:    
-define(Opts1, #server_opts{port=80}).

%% and use it anywhere in your code:

my_func() ->
     io:format("~p~n",[?Opts1]).

P.S. Using records from shell. Assume - you've created file my_server.hrl which contain definition of record server_opts. First of all you're have to load record definition, using function rr("name_of_file_with_record_definition"), after this you're ready to work with records in shell:

1> rr("my_record.hrl").
[server_opts]
2> 
2> Opts1 = #server_opts{port=80}.
#server_opts{port = 80,ip = "127.0.0.1",
             max_connections = 10}
3> 
3> Opts1.
#server_opts{port = 80,ip = "127.0.0.1",
             max_connections = 10}
4> 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top