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

There are two main types of scopes in Julia,global* scope* andlocal* 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

doblocks,letblocks, comprehensions, generators local (hard) global, local

begin blocks, if blocks only global only global

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

hard scope

第一种情况很符合直觉,函数运行后x还是123,函数内的x默认是局部变量

the hard scope rule isn't affected by anything in global scope

x=123

functiongreet()

x="hello"#newlocal

println(x)

end

greet()

x==123

第二种情况,使用global关键字声明x是全局变量,那么就修改了全局变量的x,因为全局变量中已经有了x,第二次赋值就覆盖了

x=123

functiongreet()

globalx="hello"#newlocal

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

fori=1:10

t=s+i#newlocal`t`

s=t#assignglobal`s`

end

s==55

t

#UndefVarError:tnotdefined

用global关键字,同样效果,但是思路更清晰

s=0#global

fori=1:10

t=s+i#newlocal`t`

globals=t#assignglobal`s`

end

s==55

Reference

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

可嘉:j16608819485

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容