[erlang-questions] The way of accessing record's attributes.

Raimo Niskanen raimo+erlang-questions@REDACTED
Tue Nov 8 15:41:29 CET 2016

On Tue, Nov 08, 2016 at 02:12:35PM +0100, Alex Feng wrote:
> Hi,
> Does anyone know why erlang has to attach the record's name to be able to
> access an attribute ?
> I don't understand, for example, the record "#robot" has been assigned to
> variable "Crusher", why do we have to use  "Crusher#robot.hobbies" instead
> of "Crusher.hobbies" ?

Records is a compile time syntactical sugar on tagged tuples.

So "Crusher#robot.hobbies" is translated to something like
  begin robot = element(1, Crusher), element(3, Crusher) end
if 'hobbies' is the second element of #robot.

The compiler can not know that it is the hobbies field from the #robot
record you want to extract unless told so.  You may mean the hobbies field
from the #whatever record.  It could see that it is a #robot record from an
earlier assignment in the same code and warn about it if it's not,
but in the general case it can not know what is stored in the variable
hence leaves it to be solved in runtime.

> 5> Crusher = #robot{name="Crusher", hobbies=["Crushing people","petting
> cats"]}.
> #robot{name = "Crusher",type = industrial,
> hobbies = ["Crushing people","petting cats"],
> details = []}
> 6> Crusher#robot.hobbies.
> ["Crushing people","petting cats"]
> Br,
> Alex

> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions


/ Raimo Niskanen, Erlang/OTP, Ericsson AB

More information about the erlang-questions mailing list