There are two main types of scopes in Julia,global* scope* andlocal* scope*.
Julia有全局變量作用域和局部變量作用域纽匙,函數(shù)或者一些結(jié)構(gòu)體奢入、循環(huán)體如for等是否內(nèi)部是局部環(huán)境可以參照下表虐秦。
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必須是一個(gè)獨(dú)立的局部變量。
hard scope
第一種情況很符合直覺镰官,函數(shù)運(yùn)行后x還是123椭住,函數(shù)內(nèi)的x默認(rèn)是局部變量
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關(guān)鍵字聲明x是全局變量牧挣,那么就修改了全局變量的x急前,因?yàn)槿肿兞恐幸呀?jīng)有了x,第二次賦值就覆蓋了
x=123
functiongreet()
globalx="hello"#newlocal
println(x)
end
greet()
x=="hello"
soft scope
for循環(huán)是local (soft)類型瀑构,我們先定義一個(gè)全局變量s=0裆针,然后在for循環(huán)中也有一個(gè)變量s,因?yàn)橹孛?新的賦值語句修改了全局變量s寺晌;但是全局變量中沒有t所以新建了一個(gè)局部的t世吨,并且外部是訪問不到這個(gè)t的,因?yàn)閠是局部變量呻征。
這樣寫耘婚,全局的s和局部的s可能產(chǎn)生歧義,詳細(xì)見官網(wǎng)怕犁,最好規(guī)避边篮,或者寫上 global。
s=0#global
fori=1:10
t=s+i#newlocal`t`
s=t#assignglobal`s`
end
s==55
t
#UndefVarError:tnotdefined
用global關(guān)鍵字奏甫,同樣效果戈轿,但是思路更清晰
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