Easy Tutorial
❮ Go Map Go Loops ❯

Go Language Variable Scope

The scope of a variable in Go refers to the range within the source code where the variable, which can be a constant, type, variable, function, or package, is accessible.

Variables in Go can be declared in three places:

Next, let's dive into local variables, global variables, and formal parameters in detail.


Local Variables

Variables declared within a function body are known as local variables. Their scope is limited to the function body, including parameters and return values.

In the following example, the main() function uses local variables a, b, and c:

Example

package main

import "fmt"

func main() {
   /* Declare local variables */
   var a, b, c int 

   /* Initialize parameters */
   a = 10
   b = 20
   c = a + b

   fmt.Printf("Result: a = %d, b = %d and c = %d\n", a, b, c)
}

The output of the above example is:

Result: a = 10, b = 20 and c = 30

Global Variables

Variables declared outside of any function are known as global variables. Global variables are accessible throughout the package and can be used in external packages once exported.

Global variables can be used in any function. The following example demonstrates the use of global variables:

Example

package main

import "fmt"

/* Declare a global variable */
var g int

func main() {

   /* Declare local variables */
   var a, b int

   /* Initialize parameters */
   a = 10
   b = 20
   g = a + b

   fmt.Printf("Result: a = %d, b = %d and g = %d\n", a, b, g)
}

The output of the above example is:

Result: a = 10, b = 20 and g = 30

In Go, global and local variable names can be the same, but local variables take precedence within the function. Here is an example:

Example

package main

import "fmt"

/* Declare a global variable */
var g int = 20

func main() {
   /* Declare a local variable */
   var g int = 10

   fmt.Printf("Result: g = %d\n", g)
}

The output of the above example is:

Result: g = 10

Formal Parameters

Formal parameters act as local variables within the function. Here is an example:

Example

package main

import "fmt"

/* Declare a global variable */
var a int = 20

func main() {
   /* Declare local variables in the main function */
   var a int = 10
   var b int = 20
   var c int = 0

   fmt.Printf("main() function: a = %d\n", a)
   c = sum(a, b)
   fmt.Printf("main() function: c = %d\n", c)
}

/* Function definition to add two numbers */
func sum(a, b int) int {
   fmt.Printf("sum() function: a = %d\n", a)
   fmt.Printf("sum() function: b = %d\n", b)

   return a + b
}

The output of the above example is:

main() function: a = 10
sum() function: a = 10
sum() function: b = 20
main() function: c = 30

Initializing Local and Global Variables

Different types of local and global variables have default initial values:

Data Type Default Initial Value
int 0
float32 0
pointer nil
❮ Go Map Go Loops ❯