{ }. An outer block can include one or more inner blocks. While inner blocks can use variables declared in their outer blocks, outer blocks cannot access variables declared within their inner blocks.
You can visualize nested blocks like this:
Example of Block Scope
Consider an example using themain function as the outer block. Inside this function, a variable named city is declared. An inner block is then introduced, where another variable country is declared. Within this inner block, both city and country are accessible.
country variable outside the inner block, such as in the outer block of the main function, the program will produce an error. The following code demonstrates a working scenario where only the city variable is accessed outside its inner block:
Remember, outer blocks cannot access variables declared in their inner blocks.
Local Variables
Local variables are declared within a function or any code block, including conditionals and loops. These variables are only accessible within the block or function where they are declared. The following image illustrates that local variables, when declared inside functions or blocks, are inaccessible outside and can also be defined within loops and conditional statements.
name variable is declared within the main function:
Global Variables
Global variables are declared outside of any function or code block, making them accessible throughout the entire program. They are often placed at the top of your source file. The diagram below shows that global variables, when declared at the top of the program, remain accessible throughout the program’s lifecycle.
name is declared outside of the main function, allowing it to be accessed within main.
Understanding the difference between local and global variable scopes is crucial for managing data access and avoiding unintended side effects in your Go programs.