Open In App

Scope of Variables in Go

Prerequisite: Variables in Go Programming Language

The Scope of a variable can be defined as a part of the program where a particular variable is accessible. A variable can be defined in a class, method, loop, etc. Like C/C++, in Golang all identifiers are lexically (or statically) scoped, i.e. scope of a variable can be determined at compile time. Or you can say a variable can only be called from within the block of code in which it is defined.

Golang scope rules of variables can be divided into two categories which depend on where the variables are declared:



Local Variables

Example:




// Go program to illustrate the
// local variables
package main 
  
import "fmt"
   
// main function
func main() { // from here local level scope of main function starts 
   
 // local variables inside the main function
 var myvariable1, myvariable2 int = 89, 45
   
// Display the values of the variables 
fmt.Printf("The value of myvariable1 is : %d\n"
                                    myvariable1) 
   
fmt.Printf("The value of myvariable2 is : %d\n"
                                    myvariable2) 
   
} // here local level scope of main function ends

Output:



The value of myvariable1 is : 89
The value of myvariable2 is : 45

Global Variables

Example:




// Go program to illustrate the
// global variables
package main 
  
import "fmt"
  
// global variable declaration
var myvariable1 int = 100
  
func main() { // from here local level scope starts 
  
// local variables inside the main function
var myvariable2 int = 200
  
// Display the value of global variable
fmt.Printf("The value of Global myvariable1 is : %d\n"
                          myvariable1) 
  
// Display the value of local variable
fmt.Printf("The value of Local myvariable2 is : %d\n"
                          myvariable2) 
                  
// calling the function            
display()
  
} // here local level scope ends
  
  
// taking a function
func display() { // local level starts 
        
// Display the value of global variable
fmt.Printf("The value of Global myvariable1 is : %d\n"
                          myvariable1) 
     
} // local scope ends here

Output:

The value of Global myvariable1 is : 100
The value of Local myvariable2 is : 200
The value of Global myvariable1 is : 100

Note: What will happen there exists a local variable with the same name as that of the global variable inside a function?

The answer is simple i.e. compiler will give preference to the local variable. Usually when two variable with the same name is defined then the compiler produces a compile-time error. But if the variables are defined in different scopes then the compiler allows it. Whenever there is a local variable defined with the same name as that of a global variable then the compiler will give precedence to the local variable.


Article Tags :