221 lines
28 KiB
HTML
221 lines
28 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width, initial-scale=1.0"/><title>Scope of Variables · The Julia Language</title><script>(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
||
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
|
||
|
||
ga('create', 'UA-28835595-6', 'auto');
|
||
ga('send', 'pageview');
|
||
</script><link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/4.2.0/normalize.min.css" rel="stylesheet" type="text/css"/><link href="https://fonts.googleapis.com/css?family=Lato|Roboto+Mono" rel="stylesheet" type="text/css"/><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css"/><script>documenterBaseURL=".."</script><script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js" data-main="../assets/documenter.js"></script><script src="../siteinfo.js"></script><script src="../../versions.js"></script><link href="../assets/highlightjs/default.css" rel="stylesheet" type="text/css"/><link href="../assets/documenter.css" rel="stylesheet" type="text/css"/></head><body><nav class="toc"><a href="../index.html"><img class="logo" src="../assets/logo.png" alt="The Julia Language logo"/></a><h1>The Julia Language</h1><select id="version-selector" onChange="window.location.href=this.value" style="visibility: hidden"></select><form class="search" action="../search.html"><input id="search-query" name="q" type="text" placeholder="Search docs"/></form><ul><li><a class="toctext" href="../index.html">Home</a></li><li><span class="toctext">Manual</span><ul><li><a class="toctext" href="introduction.html">Introduction</a></li><li><a class="toctext" href="getting-started.html">Getting Started</a></li><li><a class="toctext" href="variables.html">Variables</a></li><li><a class="toctext" href="integers-and-floating-point-numbers.html">Integers and Floating-Point Numbers</a></li><li><a class="toctext" href="mathematical-operations.html">Mathematical Operations and Elementary Functions</a></li><li><a class="toctext" href="complex-and-rational-numbers.html">Complex and Rational Numbers</a></li><li><a class="toctext" href="strings.html">Strings</a></li><li><a class="toctext" href="functions.html">Functions</a></li><li><a class="toctext" href="control-flow.html">Control Flow</a></li><li class="current"><a class="toctext" href="variables-and-scoping.html">Scope of Variables</a><ul class="internal"><li><a class="toctext" href="#Global-Scope-1">Global Scope</a></li><li><a class="toctext" href="#Local-Scope-1">Local Scope</a></li><li><a class="toctext" href="#Constants-1">Constants</a></li></ul></li><li><a class="toctext" href="types.html">Types</a></li><li><a class="toctext" href="methods.html">Methods</a></li><li><a class="toctext" href="constructors.html">Constructors</a></li><li><a class="toctext" href="conversion-and-promotion.html">Conversion and Promotion</a></li><li><a class="toctext" href="interfaces.html">Interfaces</a></li><li><a class="toctext" href="modules.html">Modules</a></li><li><a class="toctext" href="documentation.html">Documentation</a></li><li><a class="toctext" href="metaprogramming.html">Metaprogramming</a></li><li><a class="toctext" href="arrays.html">Multi-dimensional Arrays</a></li><li><a class="toctext" href="linear-algebra.html">Linear algebra</a></li><li><a class="toctext" href="networking-and-streams.html">Networking and Streams</a></li><li><a class="toctext" href="parallel-computing.html">Parallel Computing</a></li><li><a class="toctext" href="dates.html">Date and DateTime</a></li><li><a class="toctext" href="interacting-with-julia.html">Interacting With Julia</a></li><li><a class="toctext" href="running-external-programs.html">Running External Programs</a></li><li><a class="toctext" href="calling-c-and-fortran-code.html">Calling C and Fortran Code</a></li><li><a class="toctext" href="handling-operating-system-variation.html">Handling Operating System Variation</a></li><li><a class="toctext" href="environment-variables.html">Environment Variables</a></li><li><a class="toctext" href="embedding.html">Embedding Julia</a></li><li><a class="toctext" href="packages.html">Packages</a></li><li><a class="toctext" href="profile.html">Profiling</a></li><li><a class="toctext" href="stacktraces.html">Stack Traces</a></li><li><a class="toctext" href="performance-tips.html">Performance Tips</a></li><li><a class="toctext" href="workflow-tips.html">Workflow Tips</a></li><li><a class="toctext" href="style-guide.html">Style Guide</a></li><li><a class="toctext" href="faq.html">Frequently Asked Questions</a></li><li><a class="toctext" href="noteworthy-differences.html">Noteworthy Differences from other Languages</a></li><li><a class="toctext" href="unicode-input.html">Unicode Input</a></li></ul></li><li><span class="toctext">Standard Library</span><ul><li><a class="toctext" href="../stdlib/base.html">Essentials</a></li><li><a class="toctext" href="../stdlib/collections.html">Collections and Data Structures</a></li><li><a class="toctext" href="../stdlib/math.html">Mathematics</a></li><li><a class="toctext" href="../stdlib/numbers.html">Numbers</a></li><li><a class="toctext" href="../stdlib/strings.html">Strings</a></li><li><a class="toctext" href="../stdlib/arrays.html">Arrays</a></li><li><a class="toctext" href="../stdlib/parallel.html">Tasks and Parallel Computing</a></li><li><a class="toctext" href="../stdlib/linalg.html">Linear Algebra</a></li><li><a class="toctext" href="../stdlib/constants.html">Constants</a></li><li><a class="toctext" href="../stdlib/file.html">Filesystem</a></li><li><a class="toctext" href="../stdlib/io-network.html">I/O and Network</a></li><li><a class="toctext" href="../stdlib/punctuation.html">Punctuation</a></li><li><a class="toctext" href="../stdlib/sort.html">Sorting and Related Functions</a></li><li><a class="toctext" href="../stdlib/pkg.html">Package Manager Functions</a></li><li><a class="toctext" href="../stdlib/dates.html">Dates and Time</a></li><li><a class="toctext" href="../stdlib/iterators.html">Iteration utilities</a></li><li><a class="toctext" href="../stdlib/test.html">Unit Testing</a></li><li><a class="toctext" href="../stdlib/c.html">C Interface</a></li><li><a class="toctext" href="../stdlib/libc.html">C Standard Library</a></li><li><a class="toctext" href="../stdlib/libdl.html">Dynamic Linker</a></li><li><a class="toctext" href="../stdlib/profile.html">Profiling</a></li><li><a class="toctext" href="../stdlib/stacktraces.html">StackTraces</a></li><li><a class="toctext" href="../stdlib/simd-types.html">SIMD Support</a></li></ul></li><li><span class="toctext">Developer Documentation</span><ul><li><a class="toctext" href="../devdocs/reflection.html">Reflection and introspection</a></li><li><span class="toctext">Documentation of Julia's Internals</span><ul><li><a class="toctext" href="../devdocs/init.html">Initialization of the Julia runtime</a></li><li><a class="toctext" href="../devdocs/ast.html">Julia ASTs</a></li><li><a class="toctext" href="../devdocs/types.html">More about types</a></li><li><a class="toctext" href="../devdocs/object.html">Memory layout of Julia Objects</a></li><li><a class="toctext" href="../devdocs/eval.html">Eval of Julia code</a></li><li><a class="toctext" href="../devdocs/callconv.html">Calling Conventions</a></li><li><a class="toctext" href="../devdocs/compiler.html">High-level Overview of the Native-Code Generation Process</a></li><li><a class="toctext" href="../devdocs/functions.html">Julia Functions</a></li><li><a class="toctext" href="../devdocs/cartesian.html">Base.Cartesian</a></li><li><a class="toctext" href="../devdocs/meta.html">Talking to the compiler (the <code>:meta</code> mechanism)</a></li><li><a class="toctext" href="../devdocs/subarrays.html">SubArrays</a></li><li><a class="toctext" href="../devdocs/sysimg.html">System Image Building</a></li><li><a class="toctext" href="../devdocs/llvm.html">Working with LLVM</a></li><li><a class="toctext" href="../devdocs/stdio.html">printf() and stdio in the Julia runtime</a></li><li><a class="toctext" href="../devdocs/boundscheck.html">Bounds checking</a></li><li><a class="toctext" href="../devdocs/locks.html">Proper maintenance and care of multi-threading locks</a></li><li><a class="toctext" href="../devdocs/offset-arrays.html">Arrays with custom indices</a></li><li><a class="toctext" href="../devdocs/libgit2.html">Base.LibGit2</a></li><li><a class="toctext" href="../devdocs/require.html">Module loading</a></li></ul></li><li><span class="toctext">Developing/debugging Julia's C code</span><ul><li><a class="toctext" href="../devdocs/backtraces.html">Reporting and analyzing crashes (segfaults)</a></li><li><a class="toctext" href="../devdocs/debuggingtips.html">gdb debugging tips</a></li><li><a class="toctext" href="../devdocs/valgrind.html">Using Valgrind with Julia</a></li><li><a class="toctext" href="../devdocs/sanitizers.html">Sanitizer support</a></li></ul></li></ul></li></ul></nav><article id="docs"><header><nav><ul><li>Manual</li><li><a href="variables-and-scoping.html">Scope of Variables</a></li></ul><a class="edit-page" href="https://github.com/JuliaLang/julia/tree/d386e40c17d43b79fc89d3e579fc04547241787c/doc/src/manual/variables-and-scoping.md"><span class="fa"></span> Edit on GitHub</a></nav><hr/><div id="topbar"><span>Scope of Variables</span><a class="fa fa-bars" href="#"></a></div></header><h1><a class="nav-anchor" id="scope-of-variables-1" href="#scope-of-variables-1">Scope of Variables</a></h1><p>The <em>scope</em> of a variable is the region of code within which a variable is visible. Variable scoping helps avoid variable naming conflicts. The concept is intuitive: two functions can both have arguments called <code>x</code> without the two <code>x</code>'s referring to the same thing. Similarly there are many other cases where different blocks of code can use the same name without referring to the same thing. The rules for when the same variable name does or doesn't refer to the same thing are called scope rules; this section spells them out in detail.</p><p>Certain constructs in the language introduce <em>scope blocks</em>, which are regions of code that are eligible to be the scope of some set of variables. The scope of a variable cannot be an arbitrary set of source lines; instead, it will always line up with one of these blocks. There are two main types of scopes in Julia, <em>global scope</em> and <em>local scope</em>, the latter can be nested. The constructs introducing scope blocks are:</p><table><tr><th>Scope name</th><th>block/construct introducing this kind of scope</th></tr><tr><td><a href="variables-and-scoping.html#Global-Scope-1">Global Scope</a></td><td><code>module</code>, <code>baremodule</code>, at interactive prompt (REPL)</td></tr><tr><td><a href="variables-and-scoping.html#Local-Scope-1">Local Scope</a></td><td><a href="variables-and-scoping.html#Soft-Local-Scope-1">Soft Local Scope</a>: <code>for</code>, <code>while</code>, comprehensions, try-catch-finally, <code>let</code></td></tr><tr><td><a href="variables-and-scoping.html#Local-Scope-1">Local Scope</a></td><td><a href="variables-and-scoping.html#Hard-Local-Scope-1">Hard Local Scope</a>: functions (either syntax, anonymous & do-blocks), <code>struct</code>, <code>macro</code></td></tr></table><p>Notably missing from this table are <a href="control-flow.html#man-compound-expressions-1">begin blocks</a> and <a href="control-flow.html#man-conditional-evaluation-1">if blocks</a>, which do <em>not</em> introduce new scope blocks. All three types of scopes follow somewhat different rules which will be explained below as well as some extra rules for certain blocks.</p><p>Julia uses <a href="https://en.wikipedia.org/wiki/Scope_%28computer_science%29#Lexical_scoping_vs._dynamic_scoping">lexical scoping</a>, meaning that a function's scope does not inherit from its caller's scope, but from the scope in which the function was defined. For example, in the following code the <code>x</code> inside <code>foo</code> refers to the <code>x</code> in the global scope of its module <code>Bar</code>:</p><pre><code class="language-jldoctest">julia> module Bar
|
||
x = 1
|
||
foo() = x
|
||
end;</code></pre><p>and not a <code>x</code> in the scope where <code>foo</code> is used:</p><pre><code class="language-jldoctest">julia> import .Bar
|
||
|
||
julia> x = -1;
|
||
|
||
julia> Bar.foo()
|
||
1</code></pre><p>Thus <em>lexical scope</em> means that the scope of variables can be inferred from the source code alone.</p><h2><a class="nav-anchor" id="Global-Scope-1" href="#Global-Scope-1">Global Scope</a></h2><p><em>Each module introduces a new global scope</em>, separate from the global scope of all other modules; there is no all-encompassing global scope. Modules can introduce variables of other modules into their scope through the <a href="modules.html#modules-1">using or import</a> statements or through qualified access using the dot-notation, i.e. each module is a so-called <em>namespace</em>. Note that variable bindings can only be changed within their global scope and not from an outside module.</p><pre><code class="language-julia-repl">julia> module A
|
||
a = 1 # a global in A's scope
|
||
end;
|
||
|
||
julia> module B
|
||
module C
|
||
c = 2
|
||
end
|
||
b = C.c # can access the namespace of a nested global scope
|
||
# through a qualified access
|
||
import ..A # makes module A available
|
||
d = A.a
|
||
end;
|
||
|
||
julia> module D
|
||
b = a # errors as D's global scope is separate from A's
|
||
end;
|
||
ERROR: UndefVarError: a not defined
|
||
|
||
julia> module E
|
||
import ..A # make module A available
|
||
A.a = 2 # throws below error
|
||
end;
|
||
ERROR: cannot assign variables in other modules</code></pre><p>Note that the interactive prompt (aka REPL) is in the global scope of the module <code>Main</code>.</p><h2><a class="nav-anchor" id="Local-Scope-1" href="#Local-Scope-1">Local Scope</a></h2><p>A new local scope is introduced by most code-blocks, see above table for a complete list. A local scope <em>usually</em> inherits all the variables from its parent scope, both for reading and writing. There are two subtypes of local scopes, hard and soft, with slightly different rules concerning what variables are inherited. Unlike global scopes, local scopes are not namespaces, thus variables in an inner scope cannot be retrieved from the parent scope through some sort of qualified access.</p><p>The following rules and examples pertain to both hard and soft local scopes. A newly introduced variable in a local scope does not back-propagate to its parent scope. For example, here the <code>z</code> is not introduced into the top-level scope:</p><pre><code class="language-julia-repl">julia> for i = 1:10
|
||
z = i
|
||
end
|
||
|
||
julia> z
|
||
ERROR: UndefVarError: z not defined</code></pre><p>(Note, in this and all following examples it is assumed that their top-level is a global scope with a clean workspace, for instance a newly started REPL.)</p><p>Inside a local scope a variable can be forced to be a local variable using the <code>local</code> keyword:</p><pre><code class="language-julia-repl">julia> x = 0;
|
||
|
||
julia> for i = 1:10
|
||
local x
|
||
x = i + 1
|
||
end
|
||
|
||
julia> x
|
||
0</code></pre><p>Inside a local scope a new global variable can be defined using the keyword <code>global</code>:</p><pre><code class="language-julia-repl">julia> for i = 1:10
|
||
global z
|
||
z = i
|
||
end
|
||
|
||
julia> z
|
||
10</code></pre><p>The location of both the <code>local</code> and <code>global</code> keywords within the scope block is irrelevant. The following is equivalent to the last example (although stylistically worse):</p><pre><code class="language-julia-repl">julia> for i = 1:10
|
||
z = i
|
||
global z
|
||
end
|
||
|
||
julia> z
|
||
10</code></pre><h3><a class="nav-anchor" id="Soft-Local-Scope-1" href="#Soft-Local-Scope-1">Soft Local Scope</a></h3><blockquote><p>In a soft local scope, all variables are inherited from its parent scope unless a variable is specifically marked with the keyword <code>local</code>.</p></blockquote><p>Soft local scopes are introduced by for-loops, while-loops, comprehensions, try-catch-finally-blocks, and let-blocks. There are some extra rules for <a href="variables-and-scoping.html#Let-Blocks-1">Let Blocks</a> and for <a href="variables-and-scoping.html#For-Loops-and-Comprehensions-1">For Loops and Comprehensions</a>.</p><p>In the following example the <code>x</code> and <code>y</code> refer always to the same variables as the soft local scope inherits both read and write variables:</p><pre><code class="language-julia-repl">julia> x, y = 0, 1;
|
||
|
||
julia> for i = 1:10
|
||
x = i + y + 1
|
||
end
|
||
|
||
julia> x
|
||
12</code></pre><p>Within soft scopes, the <em>global</em> keyword is never necessary, although allowed. The only case when it would change the semantics is (currently) a syntax error:</p><pre><code class="language-julia-repl">julia> let
|
||
local j = 2
|
||
let
|
||
global j = 3
|
||
end
|
||
end
|
||
ERROR: syntax: `global j`: j is local variable in the enclosing scope</code></pre><h3><a class="nav-anchor" id="Hard-Local-Scope-1" href="#Hard-Local-Scope-1">Hard Local Scope</a></h3><p>Hard local scopes are introduced by function definitions (in all their forms), struct type definition blocks, and macro-definitions.</p><blockquote><p>In a hard local scope, all variables are inherited from its parent scope unless:</p><ul><li><p>an assignment would result in a modified <em>global</em> variable, or</p></li><li><p>a variable is specifically marked with the keyword <code>local</code>.</p></li></ul></blockquote><p>Thus global variables are only inherited for reading but not for writing:</p><pre><code class="language-julia-repl">julia> x, y = 1, 2;
|
||
|
||
julia> function foo()
|
||
x = 2 # assignment introduces a new local
|
||
return x + y # y refers to the global
|
||
end;
|
||
|
||
julia> foo()
|
||
4
|
||
|
||
julia> x
|
||
1</code></pre><p>An explicit <code>global</code> is needed to assign to a global variable:</p><pre><code class="language-julia-repl">julia> x = 1;
|
||
|
||
julia> function foobar()
|
||
global x = 2
|
||
end;
|
||
|
||
julia> foobar();
|
||
|
||
julia> x
|
||
2</code></pre><p>Note that <em>nested functions</em> can behave differently to functions defined in the global scope as they can modify their parent scope's <em>local</em> variables:</p><pre><code class="language-julia-repl">julia> x, y = 1, 2;
|
||
|
||
julia> function baz()
|
||
x = 2 # introduces a new local
|
||
function bar()
|
||
x = 10 # modifies the parent's x
|
||
return x + y # y is global
|
||
end
|
||
return bar() + x # 12 + 10 (x is modified in call of bar())
|
||
end;
|
||
|
||
julia> baz()
|
||
22
|
||
|
||
julia> x, y
|
||
(1, 2)</code></pre><p>The distinction between inheriting global and local variables for assignment can lead to some slight differences between functions defined in local vs. global scopes. Consider the modification of the last example by moving <code>bar</code> to the global scope:</p><pre><code class="language-julia-repl">julia> x, y = 1, 2;
|
||
|
||
julia> function bar()
|
||
x = 10 # local
|
||
return x + y
|
||
end;
|
||
|
||
julia> function quz()
|
||
x = 2 # local
|
||
return bar() + x # 12 + 2 (x is not modified)
|
||
end;
|
||
|
||
julia> quz()
|
||
14
|
||
|
||
julia> x, y
|
||
(1, 2)</code></pre><p>Note that above subtlety does not pertain to type and macro definitions as they can only appear at the global scope. There are special scoping rules concerning the evaluation of default and keyword function arguments which are described in the <a href="functions.html#man-functions-1">Function section</a>.</p><p>An assignment introducing a variable used inside a function, type or macro definition need not come before its inner usage:</p><pre><code class="language-julia-repl">julia> f = y -> y + a
|
||
(::#1) (generic function with 1 method)
|
||
|
||
julia> f(3)
|
||
ERROR: UndefVarError: a not defined
|
||
Stacktrace:
|
||
[1] (::##1#2)(::Int64) at ./none:1
|
||
|
||
julia> a = 1
|
||
1
|
||
|
||
julia> f(3)
|
||
4</code></pre><p>This behavior may seem slightly odd for a normal variable, but allows for named functions – which are just normal variables holding function objects – to be used before they are defined. This allows functions to be defined in whatever order is intuitive and convenient, rather than forcing bottom up ordering or requiring forward declarations, as long as they are defined by the time they are actually called. As an example, here is an inefficient, mutually recursive way to test if positive integers are even or odd:</p><pre><code class="language-julia-repl">julia> even(n) = n == 0 ? true : odd(n-1);
|
||
|
||
julia> odd(n) = n == 0 ? false : even(n-1);
|
||
|
||
julia> even(3)
|
||
false
|
||
|
||
julia> odd(3)
|
||
true</code></pre><p>Julia provides built-in, efficient functions to test for oddness and evenness called <a href="../stdlib/numbers.html#Base.iseven"><code>iseven()</code></a> and <a href="../stdlib/numbers.html#Base.isodd"><code>isodd()</code></a> so the above definitions should only be taken as examples.</p><h3><a class="nav-anchor" id="Hard-vs.-Soft-Local-Scope-1" href="#Hard-vs.-Soft-Local-Scope-1">Hard vs. Soft Local Scope</a></h3><p>Blocks which introduce a soft local scope, such as loops, are generally used to manipulate the variables in their parent scope. Thus their default is to fully access all variables in their parent scope.</p><p>Conversely, the code inside blocks which introduce a hard local scope (function, type, and macro definitions) can be executed at any place in a program. Remotely changing the state of global variables in other modules should be done with care and thus this is an opt-in feature requiring the <code>global</code> keyword.</p><p>The reason to allow <em>modifying local</em> variables of parent scopes in nested functions is to allow constructing <a href="https://en.wikipedia.org/wiki/Closure_%28computer_programming%29">closures</a> which have a private state, for instance the <code>state</code> variable in the following example:</p><pre><code class="language-julia-repl">julia> let
|
||
state = 0
|
||
global counter
|
||
counter() = state += 1
|
||
end;
|
||
|
||
julia> counter()
|
||
1
|
||
|
||
julia> counter()
|
||
2</code></pre><p>See also the closures in the examples in the next two sections.</p><h3><a class="nav-anchor" id="Let-Blocks-1" href="#Let-Blocks-1">Let Blocks</a></h3><p>Unlike assignments to local variables, <code>let</code> statements allocate new variable bindings each time they run. An assignment modifies an existing value location, and <code>let</code> creates new locations. This difference is usually not important, and is only detectable in the case of variables that outlive their scope via closures. The <code>let</code> syntax accepts a comma-separated series of assignments and variable names:</p><pre><code class="language-julia-repl">julia> x, y, z = -1, -1, -1;
|
||
|
||
julia> let x = 1, z
|
||
println("x: $x, y: $y") # x is local variable, y the global
|
||
println("z: $z") # errors as z has not been assigned yet but is local
|
||
end
|
||
x: 1, y: -1
|
||
ERROR: UndefVarError: z not defined</code></pre><p>The assignments are evaluated in order, with each right-hand side evaluated in the scope before the new variable on the left-hand side has been introduced. Therefore it makes sense to write something like <code>let x = x</code> since the two <code>x</code> variables are distinct and have separate storage. Here is an example where the behavior of <code>let</code> is needed:</p><pre><code class="language-julia-repl">julia> Fs = Array{Any}(2); i = 1;
|
||
|
||
julia> while i <= 2
|
||
Fs[i] = ()->i
|
||
i += 1
|
||
end
|
||
|
||
julia> Fs[1]()
|
||
3
|
||
|
||
julia> Fs[2]()
|
||
3</code></pre><p>Here we create and store two closures that return variable <code>i</code>. However, it is always the same variable <code>i</code>, so the two closures behave identically. We can use <code>let</code> to create a new binding for <code>i</code>:</p><pre><code class="language-julia-repl">julia> Fs = Array{Any}(2); i = 1;
|
||
|
||
julia> while i <= 2
|
||
let i = i
|
||
Fs[i] = ()->i
|
||
end
|
||
i += 1
|
||
end
|
||
|
||
julia> Fs[1]()
|
||
1
|
||
|
||
julia> Fs[2]()
|
||
2</code></pre><p>Since the <code>begin</code> construct does not introduce a new scope, it can be useful to use a zero-argument <code>let</code> to just introduce a new scope block without creating any new bindings:</p><pre><code class="language-julia-repl">julia> let
|
||
local x = 1
|
||
let
|
||
local x = 2
|
||
end
|
||
x
|
||
end
|
||
1</code></pre><p>Since <code>let</code> introduces a new scope block, the inner local <code>x</code> is a different variable than the outer local <code>x</code>.</p><h3><a class="nav-anchor" id="For-Loops-and-Comprehensions-1" href="#For-Loops-and-Comprehensions-1">For Loops and Comprehensions</a></h3><p><code>for</code> loops and <a href="arrays.html#Comprehensions-1">Comprehensions</a> have the following behavior: any new variables introduced in their body scopes are freshly allocated for each loop iteration. This is in contrast to <code>while</code> loops which reuse the variables for all iterations. Therefore these constructs are similar to <code>while</code> loops with <code>let</code> blocks inside:</p><pre><code class="language-julia-repl">julia> Fs = Array{Any}(2);
|
||
|
||
julia> for j = 1:2
|
||
Fs[j] = ()->j
|
||
end
|
||
|
||
julia> Fs[1]()
|
||
1
|
||
|
||
julia> Fs[2]()
|
||
2</code></pre><p><code>for</code> loops will reuse existing variables for its iteration variable:</p><pre><code class="language-julia-repl">julia> i = 0;
|
||
|
||
julia> for i = 1:3
|
||
end
|
||
|
||
julia> i
|
||
3</code></pre><p>However, comprehensions do not do this, and always freshly allocate their iteration variables:</p><pre><code class="language-julia-repl">julia> x = 0;
|
||
|
||
julia> [ x for x = 1:3 ];
|
||
|
||
julia> x
|
||
0</code></pre><h2><a class="nav-anchor" id="Constants-1" href="#Constants-1">Constants</a></h2><p>A common use of variables is giving names to specific, unchanging values. Such variables are only assigned once. This intent can be conveyed to the compiler using the <code>const</code> keyword:</p><pre><code class="language-julia-repl">julia> const e = 2.71828182845904523536;
|
||
|
||
julia> const pi = 3.14159265358979323846;</code></pre><p>The <code>const</code> declaration is allowed on both global and local variables, but is especially useful for globals. It is difficult for the compiler to optimize code involving global variables, since their values (or even their types) might change at almost any time. If a global variable will not change, adding a <code>const</code> declaration solves this performance problem.</p><p>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 for performance purposes.</p><p>Special top-level assignments, such as those performed by the <code>function</code> and <code>struct</code> keywords, are constant by default.</p><p>Note that <code>const</code> only affects the variable binding; the variable may be bound to a mutable object (such as an array), and that object may still be modified.</p><footer><hr/><a class="previous" href="control-flow.html"><span class="direction">Previous</span><span class="title">Control Flow</span></a><a class="next" href="types.html"><span class="direction">Next</span><span class="title">Types</span></a></footer></article></body></html>
|