Scope of Variables in Go
Overview
We often have to deal with variables and their scope in the programming world. The Scope of the variable tells about the accessibility of that variable from a piece of code. In this article, we will learn about the scope of variables in Golang. We will also discuss Local and Global variables in Golang.
Introduction
Variables are the nouns of a programming language, all variables in Golang have a data type. A variable's data type determines the values that the variable can hold and the operations that can be performed on that variable.
In Golang, the var keyword is used to declare variables. Below is the syntax to declare a variable in Golang.
Scope of a Variable
A Golang variable scope is a part of the code where a specified variable can be accessed and modified. In abstract terms, the scope of a variable is its lifetime in the program.
Golang variable scope can be divided into two categories based on where they were declared:
- Local Variables
- Global Variables
Local Variables
Golang Variables which are declared inside a function or a block of code are called Local Variables. These Variables are not visible outside the block of code.
Local Variables can be declared inside a function, loops, and nested code. For variables declared in nested loops higher order can not access the variables of lower order loops, but lower order loops can access all the variables from the parent loops.
These Variables are not accessible once the function or block of code is executed. There will be a compile-time error if Local variables are declared twice in the same scope.
Example for local variable:
Output:
Example for Local scope: local space example link
Global Variable
Global Variables are defined outside of a function or a block of code. Generally, they are declared at the top of our Go file. Global variables can be accessed from any function throughout the lifetime of the program and can be accessed by any function defined in our code.
Example for Global variable:
Output:
Example for Global variable : global scope example link
Global and Local Variables of the Same Name
When we declare both Local and Global variables with the same name. The preference goes to the local variable and that will be used when our application is executed. This phenomenon is called Variable Shadowing.
Output:
Example: example link
Conclusion
- Understood Golang variable scopes.
- Learnt types of variable scopes in Golang.
- Implemented examples showing scopes.