[erlang-questions] record with dynamic item name

Jachym Holecek freza@REDACTED
Sun Aug 28 20:13:11 CEST 2011

# Roberto Ostinelli 2011-08-28:
> is there any way to retrieve a record item whose identifier is in a variable?
> For instance:
> -record(state, {
>     type = 1
> }).
> These do not work:
> Type = type,
> Val = #state.Type.
> nor
> #state{Type = Val}.

If you're already passing Type to the common extraction routine, perhaps you
could pass field position (#state.type) instead of field name (type) and use
element/2 to extract it. If the names are fixed, but their positions vary you
can use record_info/2 as Michael suggests.

Alternatively you could establish the horribly fragile convention of fixing
positions of "shared" fields among a family of records and wait for subtle
bugs to emerge in live systems over time (well, it doesn't have to be this
pessimistic, but...). :-)

In the most general case, I would say you're using the wrong data structure
for the job or your APIs need a slight redesign -- is the code where you
need this publically available somewhere by any chance?

	-- Jachym

More information about the erlang-questions mailing list