Understanding scope in Golang

What is scope?
Scope can be defined as the current context of execution in which values and expressions are “visible” or can be accessed within a program. If a variable or expression is not in the current scope,it will not be available for use by other parts of the program.
There exists two types of scope in Go:
Local scope
Local scope is achieved when a variable is declared inside a function body. Such variables are said to have local scope thus (within the function). They can not be accessed outside of the function.
These types of variables are called local variables. For example,
| |
Global scope
When a variable is declared outside of a function body, it possesses a global scope. Such variables are know as global variables. They can be accessed from any part of a program. For example,
| |
Why is scope important in a program?
- Scope helps to prevent mutation of assigned values during the lifetime of a program which helps avoid unneccessary bugs in a program.
What happens if a variable has the same name in both the global and local scope?
If we have local and global variables with the same variable names, the compiler gives priority to the local variable. For example,
| |
Output
| |