Field assignments are reordered in record creations

Romain Lenglet rlenglet@REDACTED
Mon May 22 08:56:34 CEST 2006


I just remarked that in a record creation expression, the fields 
assignments are reordered to match the record definition. This 
is significant if the fields assignments have side effects (e.g. 
read from a file).

For instance, executing:

-module(test1).
-record(rec, {foo, bar}).
-export([start/0]).
start() ->
    #rec{foo = io:format("foo"), bar = io:format("bar")}.

outputs:

foobar{rec,ok,ok}

But executing:
...
-record(rec, {bar, foo}).
...
    #rec{foo = io:format("foo"), bar = io:format("bar")}.

outputs:

barfoo{rec,ok,ok}

Only the order of fields in the record definition changed, but 
the side effects are different.

Just to demonstrate that the order of assigments in a record 
creation is not significant, executing:

...
-record(rec, {foo, bar}).
...
    #rec{bar = io:format("bar"), foo = io:format("foo")}.

outputs:

foobar{rec,ok,ok}


The Erlang Reference Manual only says:
"The fields may be in any order, not necessarily the same order 
as in the record definition, and fields can be omitted."

Please someone also add that field assignments are reordered to 
match the order of fields in the record definition.  This is not 
obvious.

-- 
Romain LENGLET



More information about the erlang-questions mailing list