concept scope in category go

appears as: scope, scopes, scope, The scope
Get Programming with Go

This is an excerpt from Manning's book Get Programming with Go.

4.1. Looking into scope

When a variable is declared, it comes into scope, or to put it another way, the variable becomes visible. Your program can access the variable so long as it’s in scope, but once a variable is no longer in scope, attempts to access it will report an error.

Scoping also helps while reading through code because you don’t need to keep all the variables in your head. Once a variable goes out of scope, you can stop thinking about that variable.

In Go, scopes tend to begin and end along the lines of curly braces {}. In the following listing, the main function begins a scope, and the for loop begins a nested scope.

Listing 4.1. Scoping rules: scope.go
package main

import (
    "fmt"
    "math/rand"
)

func main() {
    var count = 0

    for count < 10 {                      #1
        var num = rand.Intn(10) + 1
        fmt.Println(num)

        count++
    }                                     #2
}

The count variable is declared within the function scope and is visible until the end of the main function, whereas the num variable is declared within the scope of the for loop. After the loop ends, the num variable goes out of scope.

The Go compiler will report an error for any attempt to access num after the loop. You can access the count variable after the for loop ends because it’s declared outside of the loop, though there really is no reason to. In order to confine count to the scope of a loop, you’ll need a different way to declare variables in Go.