Scope of variables in Julia
In this chapter, we will illustrate some variable scoping issues that might not be obvious to all Julia users. A variable can be defined in one of two scopes—either local or global.
Getting ready
For this recipe, you do not need to install any packages.
Note
In the GitHub repository for this recipe you will find the commands.txt
file that contains the presented sequence of Julia commands.
How to do it...
To test how variable scoping works in Julia, follow the steps:
- Firstly, to illustrate variable scoping in Julia, run the following code:
julia>a, b=1, 2; julia>leta=30, b=40 letb=500 println("inner scope $a $b") end println("outer scope $a $b") end innerscope30500 outerscope3040 julia>println("global scope $a $b") globalscope12
We can see that with each scoping level (created by a let...end
block), the meaning of variables changes. The let
statement creates a new scope for variables.
- Observe the following code:
julia>x=5; julia>let println(x+1) end...