for循环中变量的行为已更改

时间:2018-08-14 08:03:56

标签: julia

考虑此源代码

putItem

考虑版本0.6的输出

println("Julia language version ",VERSION)
i=666
for i = 1:2
    println("i is $i")
end
println("global i is $i")

function main()
    j = 666
    for j = 1:2
        println("j is $j")
    end
    println("global j is $j")
end

main() 

与版本1.0的输出进行比较

Julia language version 0.6.3
i is 1
i is 2
global i is 2
j is 1
j is 2
global j is 2

我无法像在0.6版本中那样使用for循环来更改变量i和变量j的值

我认为C程序员会一生震惊...

1 个答案:

答案 0 :(得分:4)

如果您使用Julia 0.7(基本上是== 1.0弃用),您将看到针对预期行为更改的必要弃用消息:

┌ Warning: Deprecated syntax `implicit assignment to global variable `i``.
│ Use `global i` instead.
└ @ none:0
┌ Warning: Loop variable `i` overwrites a variable in an enclosing scope. In the future the variable will be local to the loop instead.
└ @ none:0
i is 1
i is 2
global i is 2

所以要得到想要的东西,你可以写:

function main()
    global j = 666
    for j = 1:2
        println("j is $j")
    end
    println("global j is $j")
end

main() 

理论上,应该使用https://docs.julialang.org/en/latest/manual/variables-and-scoping/#For-Loops-and-Comprehensions-1中所述的for outer i..处理您在全局级别上的第一个示例,但目前在REPL中未处理。看到此问题:https://github.com/JuliaLang/julia/issues/24293