在Julia中,是否有一种方法可以将变量从本地范围传递到封闭的本地范围? [英] In Julia, is there a way to pass a variable from a local scope to the enclosing local scope?
问题描述
我正在编写一些Julia代码,并包装在一个函数中以提高性能.我需要将在循环中创建的变量传递给外部循环,但是出于性能原因,我想避免使用全局变量:
I am writing some Julia code, wrapped in a function for performance. I need to pass a variable created in a loop to an outer loop but would like to avoid globals for performance reasons:
function f()
for i=1:1
for j=1:1
a=2
end
println(a)
end
end
f()
由于i循环的范围不了解变量 a ,因此会引发错误.首先在有问题的范围内定义 a :
This throws an error since the scope of the i-loop does not know about the variable a. Definining a first within the scope in question works:
function f()
for i=1:1
a=0
for j=1:1
a=2
end
println(a)
end
end
f()
不过,我对这种解决方案并不满意,因为它需要预定义我要传递的每个变量.没有直接方法将变量传递到封闭范围吗?
I am not super happy with that solution though, since it requires to pre-define every variable that I want to pass. Is there no direct way to pass the variable to the enclosing scope?
推荐答案
我不认为有直接方法(除了global a = 2
您要避免的方法除外).
I don't think there is a direct way (except global a = 2
what you want to avoid).
最接近您想要的是使用local
:
The closest to what you want is to use local
:
function f()
for i=1:1
local a
for j=1:1
a=2
end
println(a)
end
end
f()
这篇关于在Julia中,是否有一种方法可以将变量从本地范围传递到封闭的本地范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!