π‘ Interview Question: Variable Shadowing in Go
π§ͺ Code Example
package main
import "fmt"
var a = 10
func main() {
age := 30
if age > 18 {
a := 47 // π Shadows the global `a` ONLY inside this `if` block
fmt.Println(a) // β 47
}
fmt.Println(a) // β 10 (prints the global `a`)
}
π Takeaways:
-
π Variable shadowing occurs when a local variable has the same name as a variable in an outer scope.
-
β Go won't throw an error β itβll just use the innermost version in the current scope.
-
π¦ Global
a
is untouched and printed outside theif
block. -
β This behavior is intentional and useful for encapsulation and temporary overrides.
π§ Memory & Stack Animation β Step by Step
// β± Program Start
π¦ Data Segment:
βββββββββββββββ
β global a=10 β βββ stays alive till program ends
βββββββββββββββ
// π main() gets called
π Stack:
ββββββββββββββββββββββββββββββ
β π§© main() Stack Frame β
β βββ age = 30 β
ββββββββββββββββββββββββββββββ
--- age > 18 is TRUE, so we enter the `if` block ---
π§± New block scope begins inside main()
π Stack:
ββββββββββββββββββββββββββββββ
β π§© main() Stack Frame β
β βββ age = 30 β
β πΈ a (shadows global) =47β βββ new `a` shadows the global
ββββββββββββββββββββββββββββββ
π¨οΈ fmt.Println(a)
π€ Output: 47 β
--- if block ends, block-scope a is destroyed ---
π Stack:
ββββββββββββββββββββββββββββββ
β π§© main() Stack Frame β
β βββ age = 30 β
ββββββββββββββββββββββββββββββ
π¨οΈ fmt.Println(a)
π€ Output: 10 β
(Back to global `a`)
--- main() ends, stack is popped ---
π Stack:
(empty)
π§Ό Program exits
π Visualization Summary
-[] π§ Global variables (like a = 10) live in the data segment.
-[] π§΅ Local variables (like age or shadowed a) live in the stack.
-[] π When a new scope is entered (if, for, function block), it pushes new variables to the stack.
-[] βοΈ Once the block ends, the shadowed variable gets popped and memory is freed.
-[] π§Ό At the end, the stack is cleared, but the data segment lives throughout the whole execution.