YouTip LogoYouTip

Go Scope Rules

Go Variable Scope |

-- Learning not just technology, but dreams!

Go Tutorial

Go Tutorial Go Introduction Go Environment Setup Go Development Tools Go Program Structure Go Basic Syntax Go Data Types Go Variables Go Constants Go Operators Go Conditional Statements Go Loop Statements Go Functions Go Variable Scope Go Arrays Go Pointers Go Structures Go Slice Go Range Go Map Go Recursion Go Type Casting Go Interfaces Go Generics Go Error Handling Go Concurrency Go File Handling Go Regular Expressions Go Type Assertion Go Inheritance Go Development Tools Go Quiz Go Modules Developing Go with VSCode

Go Functions

Go Arrays

Go Variable Scope

Scope refers to the region of the source code where a declared identifier (representing a constant, type, variable, function, or package) is accessible.

In Go, variables can be declared in three places:

  • Variables defined within a function are called local variables.
  • Variables defined outside a function are called global variables.
  • Variables defined in a function's signature are called formal parameters.

Let's examine local variables, global variables, and formal parameters in detail.


Local Variables

Variables declared inside a function body are called local variables. Their scope is limited to the function body. Parameters and return value variables are also local variables.

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 = %dn", a, b, c)
}

The output of the above example is:

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

Global Variables

Variables declared outside a function body are called global variables. Global variables can be used throughout the package and even in other packages (if exported).

Global variables can be used in any function. The following example demonstrates how to use a global variable:

Example

package main

import "fmt"

/* Declare 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 = %dn", a, b, g)
}

The output of the above example is:

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

In a Go program, global and local variables can have the same name, but the local variable within the function takes precedence. Here's an example:

Example

package main

import "fmt"

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

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

    fmt.Printf("Result: g = %dn", g)
}

The output of the above example is:

Result: g = 10

Formal Parameters

Formal parameters are treated as local variables within the function. Here's an example:

Example

package main

import "fmt"

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

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

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

/* Function definition - sum of two numbers */
func sum(a, b int) int {
    fmt.Printf("a = %d in sum()n", a)
    fmt.Printf("b = %d in sum()n", b)
    return a + b
}

The output of the above example is:

a = 10 in main()
a = 10 in sum()
b = 20 in sum()
c = 30 in main()

Initializing Local and Global Variables

The default values for different types of local and global variables are:

Data Type Default Initialization Value
int 0
float32 0
pointer nil

Go Functions

Go Arrays

4 Notes

1. #0 Grassland

mus***cn@163.com 27 Formal parameter usage, compare the a in the sum function with the a in the main function. Although 1 is added in the sum function, the value in main remains the original 10:

package main

import "fmt"

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

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

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

/* Function definition - sum of two numbers */
func sum(a, b int) int {
    a = a + 1
    fmt.Printf("a = %d in sum()n", a)
    fmt.Printf("b = %d in sum()n", b)
    return a + b
}

Output:

a = 10 in main()
a = 11 in sum()
b = 20 in sum()
a = 10 in main()
c = 31 in main()

GrasslandGrassland

mus***cn@163.com 8 years ago (2018-06-25)

2. #0 Li Keson

635***754@qq.com 100

package main

import "fmt"

func main() {
    var a int = 0
    fmt.Println("for start")
    for a := 0; a < 10; a++ {
        fmt.Println(a)
    }
    fmt.Println("for end")
    fmt.Println(a)
}

Output:

for start
0
1
2
3
4
5
6
7
8
9
for end
0

In the for loop's initialize (a := 0), the a in initialize is not the same variable as the outer a. The a in initialize is a local variable for the for loop. Therefore, after the for loop finishes, the output value of a is still 0.

package main

import "fmt"

func main() {
    var a int = 0
    fmt.Println("for start")
    for a = 0; a < 10; a++ {
        fmt.Println(a)
    }
    fmt.Println("for end")
    fmt.Println(a)
}

Output:

for start
0
1
2
3
4
5
6
7
8
9
for end
10

Now, the a in initialize is the same variable as the outer a. Therefore, after the for loop finishes, the output value of a is 10.

So, everyone must be careful when using for loops...

Li KesonLi Keson

635***754@qq.com 8 years ago (2018-10-25)

3. #0 Murphy

d20***jt@163.com 11 Global variables can be used throughout the package and even in other packages (if exported).

The following code defines a global variable Total_sum in test.go, and then references it in hello.go.

test.go:

package main

import "fmt"

var Total_sum int = 0

func Sum_test(a int, b int) int {
    fmt.Printf("%d + %d = %dn", a, b, a+b)
    Total_sum += (a + b)
    fmt.Printf("Total_sum: %dn", Total_sum)
    return a + b
}

hello.go:

package main

import (
    "fmt"
)

func main() {
    var sum int
    sum = Sum_test(2, 3)
    fmt.Printf("sum: %d; Total_sum: %dn", sum, Total_sum)
}

MurphyMurphy

d20***jt@163.com 7 years ago (2019-09-27)

4. #0 akai

lkc***@126.com 36 You can control the scope of variables using curly braces. Variables within curly braces have their own scope, and variables with the same name will shadow the outer ones.

1.

a := 5
{
    a := 3
    fmt.Println("in a = ", a)
}
fmt.Println("out a = ", a)

Output:

in a = 3
out a = 5

2.

a := 5
{
    fmt.Println("in a = ", a)
}
fmt.Println("out a = ", a)

Output:

in a = 5
out a = 5

3.

a := 5
{
    a := 3
    fmt.Println("a = ", a)
}

Output:

a declared and not used

akaiakai

lkc***@126.com 7 years ago (2019-10-30)

Click to Share Notes

Cancel

Write notes...

Image URL

Image description

Image size Γ—

Share notes

  • Nickname (Required)
  • Email (Required)
  • Reference URL

Category Navigation

← Go MethodGo Function As Values β†’