为什么Erlang静态数据结构不能更改?

3pvhb19x  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(138)

我对二郎的理解是
1.所有数据结构都是不可变的
1.某些数据结构是静态的,例如记录,即在编译时
1.一些数据结构是动态的,例如Map,即在运行时
假设所有内容都被复制,包括静态数据结构(如Map)
问题=为什么我们不能更改记录?
(猜测)答案=因为记录是在由预处理程序更改的标题宏中定义的。
(猜测)答案不正确=因为数据结构有固定的内存大小(它没有),而且与C数组不同,它不是在连续内存中,而是在一个链表中?

xriantvc

xriantvc1#

(Guess at) Answer = because the record is defined in the header macro which is changed by the pre-processor.
That's pretty close. Records are a compile time feature: a record is just a tuple with a special layout, and during compilation all record operations are converted into tuple operations.
So given this record definition:

-record(foo, {a, b = default_b}).

#foo{a = x} gets converted to {foo, x, default_b} by the compiler, and a record access such as MyRecord#foo.x becomes something like element(MyRecord, 2) . (except that it also checks that MyRecord is a foo record, and raises a badrecord error otherwise)
That's why you can't change the number of elements of a record at runtime: any code that handles such records would need to be recompiled in order to access the right fields. This is similar to how C code needs to be recompiled if you change the layout of a struct.

相关问题