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:
- 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.
- 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 code I understand that the 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:
If they are saying the same thing, what is the importance of both the points?
If they are different, can you please let me know the difference?