A scope in any programming is a region of the program where a defined variable can exist and beyond that the variable cannot be accessed. There are three places where variables can be declared in Go programming language. The first is local variables which are declared inside a function or a block. The second is global variables which are declared Outside of all functions. The last is parameters which are in the definition of function parameters. In this article, we will discuss what local variables, global variables and formal parameters are.
Variables that are declared inside a function or a block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. The following example uses local variables.
Global variables are defined outside of a function, usually on top of the program. Global variables hold their value throughout the lifetime of the program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. The following example uses both global and local variables.
A program can have the same name for local and global variables but the value of the local variable inside a function takes preference.
Parameters are treated as local variables with-in that function and they take preference over the global variables.