简体   繁体   English

“#”在Erlang中意味着什么?

[英]What does “ # ” mean in Erlang?

What does "#" mean in Erlang syntax? Erlang语法中“#”是什么意思?

For example: 例如:

 Request#radius_packet.attrs

Hash marks can mean two things in Erlang: reference to a record, or reference to a map. 哈希标记在Erlang中可能意味着两件事:引用记录或引用地图。

The specific case above is referencing a record with the variable name Request , of the type radius_packet , and accessing field attrs . 上面的具体情况是引用具有变量名称Request ,类型为radius_packet ,以及访问字段attrs This syntax mimics accessing a field on a struct or object in other languages (but be careful because it is not the same). 此语法模仿以其他语言访问结构或对象上的字段(但要小心,因为它相同)。 It is directly equivalent to referencing that field as part of a variable assignment and then using the variable. 它直接等同于将该字段作为变量赋值的一部分引用,然后使用该变量。 The three versions of some_function/1 below are all equivalent in terms of what they pass to do_something/1 : 下面some_function/1的三个版本在传递给do_something/1都是等价的:

some_function(Request = #radius_packet{attrs = Attrs}) ->
    do_something(Attrs),
    % Other things where we need Request also...

some_function(#radius_packet{attrs = Attrs}) ->
    do_something(Attrs),
    % Other things where we don't need Record...

some_function(Request) ->
    do_something(Request#radius_packet.attrs),
    % etc...

Records are a meta-syntax; 记录是一种元语法; they are a preprocessor convenience which is actually translated to tuples before compilation (which is why records are so fast). 它们是预处理器的便利,实际上在编译之前就转换为元组(这就是为什么记录如此之快)。 So given the following definition of #radius_packet{} the following version of some_function is exactly equivalent to the ones above: 因此,给定#radius_packet{}的以下定义, some_function的以下版本与上面的版本完全等效:

-record #radius_packet{serial, headers, attrs}.

some_function({radius_packet, _, _, Attrs}) ->
    do_something(Attrs),
    % Other things where we don't need Record...

The above version has simply ignored record syntax in favor of writing out the underlying tuple that will be created by the preprocessor. 上面的版本简单地忽略了记录语法,有利于写出将由预处理器创建的底层元组。

Erlang docs page on records. Erlang docs记录页面。

The other place you will see hashes is in maps. 您将看到哈希的另一个地方是地图。 Map syntax using hashes looks similar to record syntax, but without any type name between the hash and the opening curley bracket: 使用哈希的地图语法看起来类似于记录语法,但在哈希和开放的curley括号之间没有任何类型名称:

AMap#{}
ARecord#record_type{}

Erlang docs page on map expressions. Erlang docs关于地图表达式的页面。

Request is the variable the record is bound to. Request是记录绑定的变量。

# denotes the variable is a record. #表示变量是记录。

radius_packet is the name of the record. radius_packet是记录的名称。

attrs is the field you're accessing from the record. attrs是您从记录中访问的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM