Elixir变量真的不可变吗? [英] Are Elixir variables really immutable?

查看:81
本文介绍了Elixir变量真的不可变吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在戴夫·托马斯(Dave Thomas)的《 Programming Elixir》一书中,他说 Elixir强制执行不可变数据,并继续说:

In Dave Thomas's book Programming Elixir he states "Elixir enforces immutable data" and goes on to say:


在Elixir中,一旦变量引用了一个列表,例如[1,2,3],您知道它将始终引用这些相同的值(直到您重新绑定变量为止)。

In Elixir, once a variable references a list such as [1,2,3], you know it will always reference those same values (until you rebind the variable).

这听起来像除非您进行更改,否则它永远不会更改,因此我对可变性和重新绑定之间的区别感到困惑。突出差异的示例将非常有帮助。

This sounds like "it won't ever change unless you change it" so I'm confused as to what the difference between mutability and rebinding is. An example highlighting the differences would be really helpful.

推荐答案

不可移植性意味着数据结构不会改变。例如,函数 HashSet.new 返回一个空集合,只要您坚持对该集合的引用,它就永远不会成为非空的。不过,您在Elixir中可以执行的操作是丢弃对某些内容的可变引用,然后将其重新绑定到新引用。例如:

Immutability means that data structures don't change. For example the function HashSet.new returns an empty set and as long as you hold on to the reference to that set it will never become non-empty. What you can do in Elixir though is to throw away a variable reference to something and rebind it to a new reference. For example:

s = HashSet.new
s = HashSet.put(s, :element)
s # => #HashSet<[:element]>

在没有显式重新绑定的情况下,该引用下的值会发生变化,

What cannot happen is the value under that reference changing without you explicitly rebinding it:

s = HashSet.new
ImpossibleModule.impossible_function(s)
s # => #HashSet<[:element]> will never be returned, instead you always get #HashSet<[]>

与Ruby进行对比,您可以在其中执行以下操作:

Contrast this with Ruby, where you can do something like the following:

s = Set.new
s.add(:element)
s # => #<Set: {:element}>

这篇关于Elixir变量真的不可变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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