Back to Concepts Roadmap
🟡 Level 1 — Fundamentals
Foundation

Variables

Mastering variable declarations: `var`, short declaration (`:=`), automatic zero-values, and type inference.

Real-World Analogy (Mental Model)

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

Interactive RAM

Interact with the buttons below to see how Go stores variable values and pointers in memory addresses.

Variable: x (int)Address: 0x10f48a0
Stored Value:42
Pointer: p (*int)Address: 0x10f48b8
Points to address:(not declared)
Architecture & Memory MapVisual Model
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.
Step-by-Step Code

1. Three Ways to Declare Variables

Go provides flexible ways to create variables based on whether you know the initial value:

example.goGo 1.24+
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)
}
Step-by-Step Code

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.

example.goGo 1.24+
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

Mistake: Using `:=` outside of a function body at package level.
✅ Correct Way: Short declaration `:=` is only allowed inside function bodies. At package level, always use `var name = value`.
Self Assessment

Knowledge Check

Verify your understanding with these interactive practice questions.

Quizzes

Quick checks for understanding

Multiple-choice with inline explanations—expand to see why.

What is the value of `var active bool` before any assignment?
Can you use `name := "Alice"` at the top level of a Go file outside any function?

Finished this lesson?

Mark it as complete to track your overall Go mastery.