Erlang:获取记录字段值

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

我想知道Erlang中是否有一个内部函数,类似于下面发布的函数,它将给予我记录字段值而不是记录字段名称。

record_info(fields, RecordName).
q1qsirdb

q1qsirdb1#

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.

tvmytwxo

tvmytwxo2#

record_info(fields, Record) -> [Field]中的Record不能是变量,因为它必须在编译时固定。
如果需要动态处理键-值结构中的元素,请使用maps

相关问题