Does erlang implement record copy-and-modify in any clever way?

后端 未结 4 827
盖世英雄少女心
盖世英雄少女心 2021-02-10 09:13

given:

-record(foo, {a, b, c}).

I do something like this:

Thing = #foo{a={1,2}, b={3,4}, c={5,6}},
Thing1 = Thing#foo{a={7,8}}.         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-10 09:45

    I can definitely verify what people have already pointed out:

    • a record is just a tuple with the record name as the first element and all the fields just the following tuple element
    • when an element of a tuple is changed, updating a field in a record in your case, only the top level tuple is new, all the elements are just reused

    This works just because we have immutable data. So in your example each time you update a value in a #foo record none of the data in the elements are copied and only a new 4-element tuple (5 words) is created. Erlang will never does a deep copy in this type of operation or when passing arguments in function calls.

提交回复
热议问题