Stage 1 · Code
Programming Foundations
Variables & Memory
How Go stores data in memory: stack vs heap, value types.
Variable Declaration
Go offers multiple ways to declare variables. The := short declaration infers type, while var allows explicit typing and zero-value initialization.
Memory Model: Stack vs Heap
Understanding where variables live helps reason about performance and lifetime:
| Aspect | Stack | Heap |
|---|---|---|
| Allocation | Fast (pointer bump) | Slower (allocator search) |
| Deallocation | Automatic (function return) | Garbage collected |
| Lifetime | Function scope | Arbitrary (escaped pointers) |
| Size | Small, fixed per goroutine | Large, dynamic |
| Cache | Hot (L1/L2 friendly) | Colder |
Go's escape analysis tries to keep variables on the stack. If a variable's address doesn't escape the function (no pointer returned, no goroutine capture, no interface storage), it stays on the stack — faster allocation, no GC pressure.
Value Types vs Reference Types
In Go, value types hold data directly. Reference types hold pointers to underlying data structures.
| Category | Types | Assignment Behavior |
|---|---|---|
| Value | int, float, bool, string, array, struct | Copies data |
| Reference | slice, map, channel, pointer, function, interface | Copies pointer/header |
Escape Analysis in Go
The compiler decides stack vs heap via escape analysis. Run with go build -gcflags=-m to see decisions.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.