代码之家  ›  专栏  ›  技术社区  ›  nmichaels

访问记录中的字段时出现语法错误

  •  1
  • nmichaels  · 技术社区  · 14 年前

    我遇到了一个非常容易解决的问题。跟随 this ,我正在尝试访问记录中的字段。下面是一个简单的例子,展示了我的问题:

    -module(test).
    -export([test/0]).
    
    -record(rec, {f1=[], f2=[], f3=[]}).
    
    test() ->
        Rec = #rec{f1=[1,2,3], f3=[4,5,6]},
        Fields = record_info(fields, rec),
        loop(Fields, Rec).
    
    loop([Field|Fields], Rec) ->
        [Rec#rec.Field|loop(Fields, Rec)]; %% <-- This is line 12.
    loop([], _Rec) ->
        [].
    

    当我试图编译测试时,我得到一个语法错误:

    ./test.erl:12: syntax error before: Field
    

    我做错什么了?

    3 回复  |  直到 11 年前
        1
  •  2
  •   hdima    14 年前

    element/2 the first element is a record name tuple_size

    Fields = lists:zip(record_info(fields, rec),
                       lists:seq(2, record_info(size, rec)))
    

    get_record_value(Name, Record, Fields) ->
        case proplists:get_value(Name, Fields) of
            undefined ->
                undefined;
            N when is_integer(N) ->
                element(N, Record)
        end.
    
        2
  •  1
  •   Zed    14 年前
        3
  •  0
  •   Greg    11 年前

    proplists

    -module(test).
    -export([start/0]).
    -record(test, {value1, value2, value3}).
    
    start() ->
        R = #test{value1=1, value2=2, value3=3},
        Fields = record_info(fields, test),
        Values = tl(tuple_to_list(R)),
        lists:zip(Fields, Values).
    

    > c("test").
    > Proplist = test:start().
    [{value1,1},{value2,2},{value3,3}]
    

    value2

    > proplists:get_value(value2, Proplist).
    2