Erlang在记录构造时出现语法错误

9lowa7mx  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(138)

下面是一个例子:

-module(my_server).

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

Opts1 = #server_opts{port=80}.

当我尝试在Erlang shell中编译它时,它给出了一个类似syntax error before Opts1的错误。你知道上面的代码可能有什么问题吗?请注意,代码来自以下网站:Record example in Erlang

slsn1g29

slsn1g291#

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.
wh6knrhe

wh6knrhe2#

也许,您认为Opts1是一个全局常量,但在Erlang中没有全局变量。
您可以使用宏定义来拥有类似全局常量(实际上在编译时被替换)的内容:

-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]).

附言**使用shell中的记录。**假设-您已经创建了包含记录server_opts定义的文件my_server.hrl。首先您必须使用函数rr("name_of_file_with_record_definition")加载记录定义,然后您就可以在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>

相关问题