πŸ’‘ 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:

  1. πŸ”’ Variable shadowing occurs when a local variable has the same name as a variable in an outer scope.

  2. β›” Go won't throw an error β€” it’ll just use the innermost version in the current scope.

  3. πŸ“¦ Global a is untouched and printed outside the if block.

  4. βœ… 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.