为什么在Elixir / Erlang中的数据共享不适用于两个地图中的同一元组 [英] Why is data sharing in Elixir / Erlang not working for the same tuple in two maps

查看:84
本文介绍了为什么在Elixir / Erlang中的数据共享不适用于两个地图中的同一元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码

defmodule Test do
  def run do
    p1 = {1, 2}
    m1 = %{a: p1}
    m2 = %{a: p1}
    IO.puts :erts_debug.same(m1.a, m2.a)
    m3 = %{b: p1}
    IO.puts :erts_debug.same(m1.a, m3.b)
  end
end

为什么 Test.run 打印此内容

iex(1)> Test.run
true  <--- expected
false <--- not true ?!
:ok

为什么 m1.a m3.b 不是相同的内存元组?

Why are m1.a and m3.b not the same in-memory tuple?

推荐答案

现代时代更新:似乎已在≈v1.7中修复。

modern era update: seems like it was fixed in ≈v1.7.

这仅适用于Elixir。在Erlang中,元组已共享

This is true for Elixir only; in Erlang the tuple is shared:

1> Tuple = {1, 2},
1> Key1 = 1,
1> Key2 = 2,
1> Map1 = #{1 => Tuple, 2 => Tuple},
1> erts_debug:same(maps:get(Key1,Map1), maps:get(Key2,Map1)).
true

2> Key3 = 3,
2> Map2 = #{3 => Tuple},
2> erts_debug:same(maps:get(Key1,Map1), maps:get(Key3,Map2)).
true

对于Elixir,这是可能,因为内部转换为erlang 复制地图或类似。我会说这可能是向Elixir核心发布的错误报告。

For Elixir, this is probably because of internal transpiler to erlang duplicates maps or like. I’d say this could be a great bug report to Elixir core.

在您的示例中,:erts_debug.same(m1.a,m2。 a)仅由于:erts_debug.same(m1,m2)#⇒true true c>,例如地图本身共享相同的内存。

In your example :erts_debug.same(m1.a, m2.a) prints true only due to :erts_debug.same(m1, m2) #⇒ true, e.g. maps themselves share the same memory.

这篇关于为什么在Elixir / Erlang中的数据共享不适用于两个地图中的同一元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆