Skip to content

Instantly share code, notes, and snippets.

@manjeettahkur
Created January 24, 2022 13:45
Show Gist options
  • Select an option

  • Save manjeettahkur/21c62ae38be438350255465eb67a1aa1 to your computer and use it in GitHub Desktop.

Select an option

Save manjeettahkur/21c62ae38be438350255465eb67a1aa1 to your computer and use it in GitHub Desktop.
// Go is lexically scoped using blocks:
// The scope of a predeclared identifier is the universe block.
// The scope of an identifier denoting a constant, type, variable, or function (but not method) declared at top level (outside any function) is the package block.
// The scope of the package name of an imported package is the file block of the file containing the import declaration.
// The scope of an identifier denoting a method receiver, function parameter, or result variable is the function body.
// 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.
// An identifier declared in a block may be redeclared in an inner block. While the identifier of the inner declaration is in scope, it denotes the entity declared by the inner declaration.
package main
import "fmt"
func main() {
foo()
}
func foo() {
e := 0
fmt.Printf("e has value <%v> with ptr <%p>AAA\n", e, &e)
for _, e := range []int{1, 2} {
fmt.Printf("e has value <%v> with ptr <%p>BBB\n", e, &e)
e := e
fmt.Printf("e has value <%v> with ptr <%p>CCC\n", e, &e)
}
fmt.Printf("e has value <%v> with ptr <%p>DDD\n", e, &e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment