Rui Motta
Rui Motta

Reputation: 141

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

Upvotes: 4

Views: 2862

Answers (2)

dvaergiller
dvaergiller

Reputation: 815

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.

Upvotes: 5

jj1bdx
jj1bdx

Reputation: 1197

Record in record_info(fields, Record) -> [Field] cannot be a variable, because it must be fixed at the compile time.

If you need to handle the elements in a key-value structure dynamically, use maps.

Upvotes: -1

Related Questions