分享

Julia编程11:变量作用域 Scope of Variables

 生信探索 2023-04-27 发布于云南

There are two main types of scopes in Julia, global* scope* and local* scope*.

Julia有全局变量作用域和局部变量作用域,函数或者一些结构体、循环体如for等是否内部是局部环境可以参照下表。

ConstructScope typeAllowed within
module, baremoduleglobalglobal
structlocal (soft)global
for, while, trylocal (soft)global, local
macrolocal (hard)global
functionslocal (hard)global, local
do blocks, let blocks, comprehensions, generatorslocal (hard)global, local
begin blocks,  if blocksonly globalonly global

soft意思是只要不重名就行,hard必须是一个独立的局部变量。

  • hard scope

第一种情况很符合直觉,函数运行后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"
  • soft scope

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

Reference

https://docs./en/v1/manual/variables-and-scoping/

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多