Algorithm


In Go (or Golang), variable scope refers to the region of the code where a variable can be accessed or modified. The scope of a variable is determined by its declaration within the code. Go has a block-based scoping mechanism, meaning that variables declared inside a block (such as within a set of curly braces {}) are only accessible within that block.

Code Examples

#1 Go Lang Local Variables

Code - Golang Programming

// Program to illustrate local variables

package main
import "fmt"

func addNumbers() {

  // local variables
  var sum int
  
  sum = 5 + 9

}


func main() {

  addNumbers()

  // cannot access sum out of its local scope
  fmt.Println("Sum is", sum)


}
Copy The Code & Try With Live Editor

Output

x
+
cmd
undefined: sum

#2 Global Variables in Golang

Code - Golang Programming

// Program to illustrate global variable

package main
import "fmt"

// declare global variable before main function
var sum int

func addNumbers () {

  // local variable
  sum = 9 + 5
}


func main() {

  addNumbers()

  // can access sum
  fmt.Println("Sum is", sum)

}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Sum is 14
Advertisements

Demonstration


Go Lang Variable Scope