Trace lexical scope and shadowing in Go
Trace lexical scope and shadowing in Go
Lexical scope is the region of source code where a declaration can be named. An inner block can declare another variable with the same name; this hides the outer declaration within that scope without changing the outer value. Resolve names from the innermost applicable scope outward.
package main
import ( "fmt")
func main() { count := 10 { count := 20 fmt.Println(count) } fmt.Println(count)}The two declarations create distinct variables. Braces alone create an explicit block. The inner count ceases to be accessible by name after the closing brace.
Expected output:
2010Assignment versus declaration
package main
import ( "fmt")
func main() { total := 5 { total = 8 } fmt.Println(total) if total := 2; total > 0 { fmt.Println(total) } fmt.Println(total)}Using = changes an existing variable; := in a nested scope can introduce a distinct one. The initializer of an if has a scope extending through its condition and branches, not beyond the statement. A common bug is using := in a nested block when you intended to update an outer variable.
Expected output:
828Try it locally
Start with score=3 using :=. In a nested block assign score=7 using =. In another nested block declare score:=9 and print it. Print the outer score afterward.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Scope and closures 01: Trace lexical scope and shadowing in Go
Check the lesson objective before moving on.
What does an inner count := 20 do when an outer count exists?
Which statement updates a visible outer total rather than declaring a new one?