Search code examples
goscopevariable-declarationtype-declaration

Understanding variable scope in Go


I am going through the Go specification to learn the language, and these points are taken from the spec under Declarations and scope.

Though I am able to understand points 1-4, I am confused on points 5 and 6:

  1. The scope of a constant or variable identifier declared inside a function begins at the end of the ConstSpec or VarSpec (ShortVarDecl for short variable declarations) and ends at the end of the innermost containing block.
  2. The scope of a type identifier declared inside a function begins at the identifier in the TypeSpec and ends at the end of the innermost containing block.

This is the code which I used to understand scope in Go:

package main

import "fmt"

func main() {
    x := 42
    fmt.Println(x)
    {
        fmt.Println(x)
        y := "The test message"
        fmt.Println(y)
    }
    // fmt.Println(y) // outside scope of y
}

From this what I understand is scope of x is within the main function, and the scope of y is inside the opening and closing brackets after fmt.Println(x), and I cannot use y outside of the closing brackets.

If I understand it correctly, both points 4 and 5 are saying the same thing. So my questions are:

  1. If they are saying the same thing, what is the importance of both the points?

  2. If they are different, can you please let me know the difference?


Solution

  • They're making the same point, with the same rules, about two different things: the first is about variables and constants, the second is about type identifiers. So, if you declare a type inside a block, the same scoping rules apply as would apply to a variable declared at the same spot.