Go - If / Else

Beginner 10/10 Teacher 10/10 Architect 10/10

Basics

if x > 10 {
  fmt.Println("big")
} else if x == 10 {
  fmt.Println("ten")
} else {
  fmt.Println("small")
}

Short Statement

if v := compute(); v > 0 { fmt.Println(v) }

Common errors

  • Forgetting braces: Go requires braces around blocks even for single statements.
  • Shadowing variables with := inside if short statements—prefer distinct names.

Practice

  • Read an int and print “even” if divisible by 2, else “odd”.

Quick quiz

  1. Where can you place a short statement in an if?
Show answer Before the condition: if v := f(); v > 0 { ... }