There are two main types of scopes in Julia, global * scope* and local * scope*. Julia有全局变量作用域和局部变量作用域,函数或者一些结构体、循环体如for等是否内部是局部环境可以参照下表。 Construct | Scope type | Allowed within |
---|
module , baremodule | global | global | struct | local (soft) | global | for , while , try | local (soft) | global, local | macro | local (hard) | global | functions | local (hard) | global, local | do blocks, let blocks, comprehensions, generators | local (hard) | global, local | begin blocks, if blocks | only global | only global |
soft意思是只要不重名就行,hard必须是一个独立的局部变量。 第一种情况很符合直觉,函数运行后x还是123,函数内的x默认是局部变量 the hard scope rule isn't affected by anything in global scope x = 123 function greet() x = "hello" # new local println(x) end greet() x == 123
第二种情况,使用global关键字声明x是全局变量,那么就修改了全局变量的x,因为全局变量中已经有了x,第二次赋值就覆盖了 x = 123
function greet() global x = "hello" # new local println(x) end
greet() x == "hello"
for循环是local (soft)类型,我们先定义一个全局变量s=0 ,然后在for循环中也有一个变量s,因为重名所以 新的赋值语句修改了全局变量s;但是全局变量中没有t所以新建了一个局部的t,并且外部是访问不到这个t的,因为t是局部变量。 这样写,全局的s和局部的s可能产生歧义,详细见官网,最好规避,或者写上 global。 s = 0 # global
for i = 1:10 t = s + i # new local `t` s = t # assign global `s` end
s == 55 t # UndefVarError: t not defined
用global关键字,同样效果,但是思路更清晰 s = 0 # global
for i = 1:10 t = s + i # new local `t` global s = t # assign global `s` end
s == 55
Referencehttps://docs./en/v1/manual/variables-and-scoping/
|