访问记录中的字段时出现语法错误
我遇到了一个应该很容易解决的问题。在此之后,我尝试访问记录中的字段。这是一个展示我的问题的简化示例:
-module(test).
-export([test/0]).
-record(rec, {f1=[], f2=[], f3=[]}).
test() ->
Rec = #rec{f1=[1,2,3], f3=[4,5,6]},
Fields = record_info(fields, rec),
loop(Fields, Rec).
loop([Field|Fields], Rec) ->
[Rec#rec.Field|loop(Fields, Rec)]; %% <-- This is line 12.
loop([], _Rec) ->
[].
当我尝试编译测试时,我收到语法错误:
./test.erl:12: syntax error before: Field
我做错了什么?
I'm having a problem that should be stupidly easy to fix. Following this, I'm trying to access a field in a record. Here's a simplified example that exhibits my problem:
-module(test).
-export([test/0]).
-record(rec, {f1=[], f2=[], f3=[]}).
test() ->
Rec = #rec{f1=[1,2,3], f3=[4,5,6]},
Fields = record_info(fields, rec),
loop(Fields, Rec).
loop([Field|Fields], Rec) ->
[Rec#rec.Field|loop(Fields, Rec)]; %% <-- This is line 12.
loop([], _Rec) ->
[].
When I try to compile test, I get a syntax error:
./test.erl:12: syntax error before: Field
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只想枚举记录值,可以使用 element/2 和枚举从 2 (第一个元素是记录名称)到 < a href="http://www.erlang.org/doc/man/erlang.html#tuple_size-1" rel="nofollow">tuple_size(记录)。
如果您想在运行时按名称访问记录字段,您可以在编译时创建辅助 proplist,如下所示:
请注意,record_info() 始终在编译时求值。
然后使用类似于以下的函数查询字段值这:
If you only want to enumerate record values you can use element/2 and enumerate elements from 2 (the first element is a record name) to tuple_size(Record).
If you want to access record fields by name at run time you can create auxiliary proplist at compile time like this:
Note that record_info() always evaluated at compile time.
And then query field value with function similar to this:
记录在编译时转换为数组,这意味着所有字段访问也都转换为 erlang:element 调用。因此变量不能用作字段名称必须在编译时已知 - 正如 Damg 已经回答的那样。
我知道的“解决方法”要么使用 proplists、dicts 等而不是记录,要么使用 Ulf Wiger 的 exprecs< /a> 生成记录访问函数。
Records are converted into arrays in compile-time, meaning that all field accesses are converted to erlang:element calls as well. Thus variables cannot be used as field names must be known at compile-time - as Damg already answered.
The "workarounds" I am aware of are either using proplists, dicts, etc. instead of records, or use Ulf Wiger's exprecs to generate record access functions.
另一种方法是将记录转换为 proplist 并使用 proplists 库模块来迭代或访问特定字段。此示例:
将生成以下 proplist:
然后例如获取字段
value2
的值:Another way is converting the record into a proplist and using the
proplists
library module to iterate or access specific fields. This example:Will produce the following proplist:
Then for example to get value of field
value2
: