Search code examples
erlangfieldrecord

Erlang: getting record field values


I would like to know if there's an internal function in Erlang, similar to the one posted below, that will give me the record field values instead of the record field names.

record_info(fields, RecordName).

Solution

  • A record in Erlang is really a tuple with it's first element being the name of the record. After compilation is done, the record will be seen as a tuple.

    If you have this record definition:

    -record(name, [field, anotherfield]).
    

    Then you can define a value of that record type like so:

    #name{ field = value1, anotherfield = value2 }.
    

    However, the actual representation for this under the hood is this:

    {name, value1, value2}.
    

    Note that the field names are actually gone here.

    Now, if you want a list of the values for each field in the record, you can use tuple_to_list:

    [name, value1, value2] = tuple_to_list(Record).
    

    So, as jj1bdx pointed out, if you want a ; separated string of all the values, you could do something like this:

    string:join([lists:flatten(io_lib:format("~p", [T])) || T <- tl(tuple_to_list(Record))], ";").
    

    This last code snippet is stolen directly from jj1bdx.