WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Go - Scope Rules


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

  • Inside a function or a block (local variables)

  • Outside of all functions (global variables)

  • In the definition of function parameters (formal parameters)

Local Variables

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. Here all the variables a, b, and c are local to the main() function.
package main

import "fmt"

func main() {
   /* local variable declaration */
   var a, b, c int 

   /* actual initialization */
   a = 80
   b = 70
   c = a + b

   fmt.Printf ("value of a = %d, b = %d and c = %d\n", a, b, c)
}
When the above code is compiled and executed, it produces the following result
$go run main.go
value of a = 80, b = 70 and c = 150

Global Variables

Global variables are defined outside of a function, usually on top of the program.A global variable can be accessed by any function. That is, a global variable is available for use throughout the program after its declaration.
package main

import "fmt"
 
/* global variable declaration */
var F int
 
func main() {
   /* local variable declaration */
   var a, b int

   /* actual initialization */
   a = 45
   b = 30
   F = a + b

   fmt.Printf("value of a = %d, b = %d and F = %d\n", a, b, F)
}
When the above code is compiled and executed, it produces the following result
$go run main.go
value of a = 45, b = 30 and F = 75

Formal Parameters

Formal parameters are treated as local variables with-in that function and they take preference over the global variables. For example
package main

import "fmt"
 
/* global variable declaration */
var a int = 30;
 
func main() {
   /* local variable declaration in main function */
   var a int = 40
   var b int = 50
   var c int = 0

   fmt.Printf("value of a in main() = %d\n",  a);
   c = sum( a, b);
   fmt.Printf("value of c in main() = %d\n",  c);
}
/* function to add two integers */
func sum(a, b int) int {
   fmt.Printf("value of a in sum() = %d\n",  a);
   fmt.Printf("value of b in sum() = %d\n",  b);

   return a + b;
}

When the above code is compiled and executed, it produces the following result
$go run main.go
value of a in main() = 40
value of a in sum() = 40
value of b in sum() = 50
value of c in main() = 90

Initializing Local and Global Variables

Local and global variables are initialized to their default value, which is 0; while pointers are initialized to nil.

Data Type Initial Default Value
int 0
float32 0
pointer nil