erlang - 通过以编程方式指定要修改的字段来修改 Erlang 中的记录

标签 erlang record

当修改是针对我们以编程方式指定的字段时,是否有相对简单的方法来(复制和)修改 Erlang 中的记录?

例如:

-record(my_record, {foo = 0, bar = 0}).

modify_record(Record, Field, Value) ->
  Record#my_record{Field = Value}.

这样就可以执行诸如 modify_record(#my_record{foo = 1}, bar, 42) 之类的操作,或者 modify_record(some_method_that_returns_a_my_record(), foo, 3.14)

编译类似的东西我会得到类似的错误

field 'Field' is not an atom or _ in record my_record

我意识到有一些关于如何与 proplist 相互转换的示例,但我希望有更简单的东西。

最佳答案

如果您传递字段编号(而不是字段名称),这是可能的。意味着你调用函数

modify_record(MyRecord, #my_record.foo, 3.14)

而不是

modify_record(MyRecord, foo, 3.14)

(#my_record.foo 返回记录中 foo 字段的数量)。在这种情况下,您的修改记录可能是

  modify_record(R, FieldNo, Val) -> setelement(FieldNo,R,Val).

关于erlang - 通过以编程方式指定要修改的字段来修改 Erlang 中的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13188449/

相关文章:

c - 数据库系统中的文件组织和操作

iphone - 使用phonegap在iPhone上录制音频

regex - 带有 Erlang re 模块的多行正则表达式

compiler-errors - 模式匹配Erlang?

Erlang 在我的一个安装上映射语法错误

r - 在compare.linkage中设置Jaroinkler的权重

ssl - Erlang Cowboy SSL 示例

erlang - 为什么或何时应该在 Erlang 中使用 RabbitMQ、ZeroMQ 等消息队列?

haskell - 在类和记录之间进行选择

haskell - 记录字段的类型不一致