julia 模块中的变量范围是如何工作的?

How does the scope of variables in julia modules work?

运行 这个代码

module mod1
export foo

function foo()
    i=0
    for ii in 1:10
        global i+=ii
    end
    i
end

end

mod1.foo()

给出 UndefVarError: i not defined.

好像是在变量i前加上一个global:

module mod2
export bar

function bar()
    global i=0
    for ii in 1:10
        global i+=ii
    end
    i
end

end

mod2.bar()

这给出:55

为什么第一种方法不行?据我了解 for 引入了一个新的范围。因此我需要循环内的全局。但为什么我在循环外也需要它?

(我使用的是 julia 1.5.0)

正确的写法是:

module mod1
export foo

function foo()
    i=0
    for ii in 1:10
        i+=ii
    end
    i
end

end
julia> mod1.foo()
55

这里介绍了3个作用域(从最外层到最内层):

  1. 模块的全局范围 mod1
  2. 局部函数范围foo
  3. for 正文的局部范围

foorules for scoping are explained in the manual. In this particular case: when i is referred to in the for body, we first look for a variable named i defined in that same scope. Since none is found, we look for it in the enclosing scope which is the local 范围...并找到使用 i=0.

声明的变量

如果在本地 foo 作用域中没有找到名为 i 的变量,我们将不得不查看封闭作用域,即 global 作用域。在这种情况下,您必须放置 global 关键字以明确允许它(因为它会影响性能)。