Julia函数自变量引用 [英] Julia function argument by reference

查看:100
本文介绍了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!将零更改为1.

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仍在父作用域中引用其对变量.

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天全站免登陆