引用的 Julia 函数参数 [英] Julia function argument by reference

查看:19
本文介绍了引用的 Julia 函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档说

在 Julia 中,函数的所有参数都通过引用传递.

In Julia, all arguments to functions are passed by reference.

所以我很惊讶地发现这两个函数的行为有所不同:

so I was quite surprised to see a difference in the behaviour of these two functions:

function foo!(r::Array{Int64})                                                                                                                                                                                     
        r=r+1                                                                                                                                                                                                      
end


function foobar!(r::Array{Int64})                                                                                                                                                                                  
        for i=1:length(r)                                                                                                                                                                                          
                r[i]=r[i]+1                                                                                                                                                                                        
        end                                                                                                                                                                                                        
end 

这是出乎意料的不同输出:

here is the unexpectedly different output:

julia> myarray
2-element Array{Int64,1}:
 0
 0

julia> foo!(myarray);

julia> myarray
2-element Array{Int64,1}:
 0
 0

julia> foobar!(myarray);

julia> myarray
2-element Array{Int64,1}:
 1
 1

如果数组是通过引用传递的,我会期待 foo!将零更改为一.

if the array is passed by reference, I would have expected foo! to change the zeros to ones.

推荐答案

r=r+1 是一个 Assignment 语句,这意味着它重新分配了 r,因此它不再引用它在父作用域中的对.但是 r[i]=r[i]+1 变异 r 值,变异不同于赋值(这里有一个很好的描述),之后 r 仍然引用它在父作用域中的 pair 变量.

r=r+1 is an Assignment statement, this means it reallocates r, so it no longer refers to its pair in the parent scope. but r[i]=r[i]+1 Mutates r value, mutation is differ from assignment (a good description here), and after that r still refers to its pair variable in the parent scope.

这篇关于引用的 Julia 函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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