Julia function argument by reference

前端 未结 4 1674
抹茶落季
抹茶落季 2021-02-05 08:22

The docs say

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

so I was quite surprised to see a difference in the behav

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-05 09:13

    In order to mutate each variable inside an array, the broadcast . operation can be used. But be aware that each value inside the array will be changed equally thus there is no need for a for loop.

    In the case of adding 1 to each element of an array :

    a = rand(1:10, 10)
    show(a) = [4, 8, 9, 1, 4, 2, 6, 7, 1, 5]
    
    function add1!(a::Array{Int64})
        a .= a .+ 1
    end
    
    add1!(a);
    show(a) = [5, 9, 10, 2, 5, 3, 7, 8, 2, 6]
    

    Despite this, if each value of an array is needed to be changed independently then for loop with indices is inevitable.

提交回复
热议问题