Passing in record name to a function

Håkan Stenholm <>
Mon Oct 7 00:18:37 CEST 2002


Yes and no, you can't pass the field name but you can pass the index of 
the field used by the underlying tuple representation, for example:

%% update field Index in record Record
set_field(Index, Record, Value) -> setelement(Index, Record, Value).

this can then be called as:

NewRecord = set_field(#record_name.field_name, Record, NewValue)

The main limitation is that the index resolution 
(#record_name.field_name) is done at compile time (by the preprocessor) 
so if the record format is changed, the code will need to be recompiled.
#RecordName.field_name or #RecordName.FieldName might be nice but don't 
work, records don't exist in the VM, they are converted to tuples 
during compilation. Of course you still have the option to access the 
tuple directly, for example, if I have several records (different 
kinds) in a list and the first field is always a id key value  i could 
simply use

%% 2 is the position of the id field, the first  tuple position is the 
name of the record
Record = lists:keysearch(Key, 2, List)

to find the record with id = Key.



More information about the erlang-questions mailing list