Facebook   Tumblr   LinkedIn

Variable Scoping in Go


Walden Systems Geeks Corner Tutorials Variable Scoping in Go Rutherford NJ New Jersey NYC New York City North Bergen County

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.

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. Local variables are not known to functions outside their own. The following example uses local variables.

package main

import "fmt"

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

    a = 5
    b = 10
    c = a + b

fmt.Printf ("value of a = %d, b = %d and c = %d ", a, b, c)
}



Global 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.

package main

import "fmt"

/* global variable declaration */
var g int

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

    a = 5
    b = 10
    g = a + b

    fmt.Printf("value of a = %d, b = %d and g = %d ", a, b, g)
}

A program can have the same name for local and global variables but the value of the local variable inside a function takes preference.

package main

import "fmt"

/* global variable declaration */
var g int = 20

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

    /* Output of the line below is "value of g = 10 */
    fmt.Printf("value of g = %d ", g )
}

Parameters are treated as local variables with-in that function and they take preference over the global variables.

package main

import "fmt"

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

func main() {
    /* local variable declaration in main function */
    var a int = 5
    var b int = 10
    var c int = 15

    fmt.Printf("value of a in main() = %d ", a);
    c = sum( a, b);
    fmt.Printf("value of c in main() = %d ", c);
}

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

    return a + b;
}