Variables
Mastering variable declarations: `var`, short declaration (`:=`), automatic zero-values, and type inference.
“Variables are labeled storage boxes. In Go, you never get a dirty or random box from memory: if you do not put something inside, Go automatically cleans it and places a default "Zero Value" inside.”
Live Memory & Pointer Simulator
Interact with the buttons below to see how Go stores variable values and pointers in memory addresses.
Zero Values in Go: Numbers (int, float) ──> 0 / 0.0 Booleans (bool) ──> false Strings (string) ──> "" (empty string) Pointers / Slices ──> nil
Key Concepts & Rules To Remember
- Standard declaration: `var age int = 25` (explicit type).
- Short declaration: `age := 25` (type inferred automatically, only valid inside functions).
- Zero Values: uninitialized variables automatically get safe defaults (`0`, `""`, `false`, `nil`).
- Unused local variables cause compile-time errors to keep codebases lean.
1. Three Ways to Declare Variables
Go provides flexible ways to create variables based on whether you know the initial value:
package main
import "fmt"
func main() {
// 1. Explicit declaration with zero value (score becomes 0)
var score int
// 2. Explicit type with initial value
var username string = "Gopher"
// 3. Short declaration with automatic type inference (most common)
level := 10 // Go infers 'int'
isPro := true // Go infers 'bool'
fmt.Println(score, username, level, isPro)
}2. Zero Values Protect You From Garbage Memory
In C/C++, uninitialized variables contain random garbage bytes from RAM. In Go, every variable is guaranteed to start in a predictable zero state.
var count int // 0
var name string // "" (empty string)
var active bool // false
var ptr *int // nil (points to nothing safely)Common Beginner Pitfalls & Mistakes
Knowledge Check
Verify your understanding with these interactive practice questions.
Quizzes
Quick checks for understanding
Multiple-choice with inline explanations—expand to see why.
Finished this lesson?
Mark it as complete to track your overall Go mastery.