Julia Notes6 - Scope of Variables

global, local, hard, soft


Each module introduces a new global scope, separate from the global scope of all other modules—there is no all-encompassing global scope.

Note that while variable bindings can be read externally, they can only be changed within the module to which they belong.

This demonstrates some important aspects of scope: in a scope, each variable can only have one meaning, and that meaning is determined regardless of the order of expressions.


soft scope在REPL和file里有区别。



An assignment modifies an existing value location, and let creates new locations. This difference is usually not important, and is only detectable in the case of variables that outlive their scope via closures.

Loops and Comprehensions

这里的loops应该指for-loop, while不行需要自己用let做binding

In loops and comprehensions, new variables introduced in their body scopes are freshly allocated for each loop iteration, as if the loop body were surrounded by a let block


julia> function f()
           i = 0
           for outer i = 1:3
               # empty
           return i

julia> f()



The const declaration should only be used in global scope on globals. Local constants are quite different. The compiler is able to determine automatically when a local variable is constant, so local constant declarations are not necessary, and in fact are currently not supported.

Note that const only affects the variable binding;


if a method references a constant and is already compiled before the constant is changed, then it might keep using the old value: