【问题标题】:Erlang gives syntax error on record constructionErlang 在记录构造上给出语法错误
【发布时间】:2012-10-31 15:50:12
【问题描述】:

我在一个模块中有以下代码:

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

【问题讨论】:

    标签: syntax erlang record erlang-shell


    【解决方案1】:

    下面一行:

    Opts1 = #server_opts{port=80}.
    

    应该包含在函数体中:

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

    记得导出函数,这样就可以在模块外调用了:

    -export([test_records/0]).
    

    一个完整的例子如下:

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

    【讨论】:

    • 嗨罗伯托,这是为了避免副作用吗?
    • 这是因为模块在 Erlang 中的工作方式。一个模块包含一系列属性(模块名称、导出函数列表、记录定义等)和函数声明。要执行一段 Erlang 代码,您需要一个入口点(函数声明)。
    • 谢谢! :) 我想知道为什么在这个例子中没有提到这个。这就是为什么我对记录用法感到困惑。
    【解决方案2】:

    也许,你认为Opts1 是一个全局常量,但是erlang 中没有全局变量。

    您可以使用macro definitions 来获得类似全局常量的东西(实际上在编译时被替换):

    -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 中的记录。 假设 - 您创建了文件 my_server.hrl,其中包含记录 server_opts 的定义。首先你必须加载记录定义,使用函数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> 
    

    【讨论】:

    • 所以一般来说我总是需要一个函数来使用记录;对吗?
    • 是的,您总是需要在函数中包装代码的执行(除了 erlang shell 会话,您可以在其中创建变量并为其赋值而不将它们包装到函数中 - 请查看我的答案的编辑)。跨度>
    • 我想补充一点,在 shell 中你也可以使用命令 rd 定义记录:例如5> rd(人,{姓名,姓氏})。顺便说一句,如上所述,在 erlang 中,您的变量必须在函数内..好吧,如果您不考虑 erlang 宏 erlang.org/doc/reference_manual/macros.html
    猜你喜欢
    • 2013-05-20
    • 2014-06-08
    • 2014-03-02
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    相关资源
    最近更新 更多