在赋值“b = a”之后,什么时候在 Julia 中更改“a”也会更改“b”,什么时候不会?

问题描述 投票:0回答:1

假设我已经在 Julia 中运行了作业

b = a
。然后我改变
a

在什么情况下

b
会自动改变,什么时候不会?

julia variable-assignment mutation
1个回答
0
投票

假设,在运行作业

a=[1,2,3]
之后,我们运行作业
b=a
a
b
都是指向数组
[1,2,3]
所在内存的同一空间的名称。 (链式赋值产生相同的效果
b=a=[1,2,3]
。)

突变

a[1] = 42
将可变结构
[1,2,3]
更改为
[42,2,3]
。现在,
a
b
都指的是新值
[42,2,3]

后续赋值

a = 3.14159
不会更改数组
[42,2,3]
。它只是将名称
a
绑定到位于单独内存位置的不同对象(标量)。数组
[42,2,3]
仍然可以通过名称
b
访问。因此,执行
a
会使 REAPL 显示
3.14159
,执行
b
会使 REAPL 显示
[42,2,3]

因此,在 b=a 之后,其中 a 是可变结构,a 的 element 的任何突变都会影响 b 返回的值。否则,b 返回的值仍然相同。此外,如果 a 的所有元素都发生了变化,那么 b 返回的可变结构的元素也会发生变化。示例:

x = [1 2 3] ;

y = x       ;

x .= [4 5 6];    # Broadcasting changes the elements. The name x is not bound to a separate array.

julia> print(x)                                                                                                                                                           
[4 5 6]

julia> print(y)
[4 5 6]          # Therefore, y returns the same array with modified elements.

将上一个代码块与下一个代码块进行比较:

x = [1 2 3] ;

y = x       ;

x = [4 5 6];    # Julia binds the name x to a separate array.

julia> print(x)                                                                                                                                                           
[4 5 6]

julia> print(y)
[1 2 3]          # Therefore, Julia did not modify the array y refers to.

请阅读 Julia 创建者之一对在 Julia 中使用 = 运算符创建副本的回答。

© www.soinside.com 2019 - 2024. All rights reserved.