首页 > 解决方案 > 如何防止模块中的全局变量或数组?

问题描述

我从 Fortran 来到 Julia。我知道 Julia 想要阻止使用全局变量。但问题是,如何防止在模块中使用全局变量?

例如,在以下模块中,

module Mod
global AAA=zeros(1000000000)

function f(x)
change the most up to date AAA with x in some way.
return nothing
end

function g(x)
using the most up to date AAA, then change/update AAA with x in some way.
return nothing
end

end

在上面的例子中,我需要更新非常大的数组 AAA,所以我把 AAA 放在了全局中。因此 f(x) 和 g(x) 可以使用最新的 AAA 并进一步更新它们。

现在由于 Julia 不鼓励使用全局变量,所以在我的情况下,我该怎么办?

我的意思是,我是否将 AAA 放在 f(x) 和 g(x) 的参数中,从而使它们变为 f(x,AAA) 和 g(x,AAA)?

在参数中传递像 AAA 这样非常大的数组真的比将 AAA 仅仅作为全局变量更快吗?

标签: julia

解决方案


可以将相关数组传递给函数。这是您的伪代码的更新版本。

module Mod
AAA=zeros(1000000000)

function f!(ba, x) # the ! mark to indicate that ba will be  updated 
    ba[1]=x
    return nothing
end

function g!(ba, x)
    ba[1] +=x
    return nothing
end

function example()
    f!(AAA,1)
    g!(AAA,2)
    @show(AAA[1])
end


end

我正在使用我的手机,所以可能会有一些拼写错误,我无法进行基准测试,但如果你想说服自己将数组作为参数传递没有任何惩罚,你可以这样做。

添加一个 ! 当函数改变参数的内容时。此外,更改的参数放在列表中的第一位。当然,这些只是约定,但它使其他人更容易理解您的代码的意图。


推荐阅读