Reputation: 4916
Is there an easy way to get a default value from an Erlang record definition? Suppose I have something like this:
-record(specialfield, {
raw = <<"default">> :: string()
}).
I would like to have some way to retrieve the default value of the raw
field. Something like this would be very simple:
#specialfield.raw % => <<"default">>
This is not possible. I would need to instantiate a record in order to get the default value:
Afield = #specialfield{}
DefaultValue = Afeild#specialfield.raw
DefaultValue % => <<"default">>
Is there an easier way of doing this? I seems like there should be some way to retrieve the default value without having to create an instance of the record.
Upvotes: 0
Views: 1207
Reputation: 1939
Take a look at erlang - records, search section "11.8".
There's not much special about records - they're just a tuple at runtime. So to get the field raw
from the tuple of default values that is the internal representation of #specialfield{} you would use:
element(#specialfield.raw, #specialfield{}).
In this case, #specialfield.raw
is the index of the value for raw
in the #specialfield tuple. When you pass in specialfield
that resolves to a tuple in the form {specialfield, <<"default">>}
.
Upvotes: 1
Reputation: 4916
Constructing an empty record and accessing one field can be done on one line:
(#specialfield{})#specialfield.raw.
Upvotes: 1
Reputation: 18879
How about:
raw_default() -> <<"default">>.
-record(specialfield, { raw = raw_default() }).
And now you have a function with the default in it. This will be extremely fast since it is a function call to a constant value. If this is also too slow, enable inlining.
Upvotes: 3