Skip to main content

Go Ep 2: Control Flow & Loops

Rachmat Hidayat
Author
Rachmat Hidayat
Learn & sharing insights on TypeScript, Go, Kubernetes, DevOps, DevSecOps, SRE, Platform Engineering, AI/ML Engineering, and MLOps.
go - This article is part of a series.
Part 2: This Article
Unlike languages with while, do-while, and foreach, Go has only ONE keyword for looping: for. This design eliminates syntax complexity while maintaining complete control over iteration.

TL;DR (Quick Summary)
#

  • if with Initialization: You can declare temporary scoped variables directly inside an if statement: if err := doX(); err != nil.
  • switch Statements: No break required! Go automatically breaks out of switch branches unless you explicitly use fallthrough.
  • The Only Loop (for): Used as a C-style loop (for i := 0; i < 10; i++), a while loop (for condition), an infinite loop (for {}), or a range loop (for index, val := range slice).

1. if / else Branching with Short Statements
#

In Go, parenthesizing if conditions is invalid syntax. Furthermore, Go allows you to initialize a variable directly inside the if clause. The variable is scoped strictly to the if/else block.

package main

import "fmt"

func getStatus() (int, string) {
	return 200, "OK"
}

func main() {
	// 🟢 Short statement initialization inside if!
	// 'code' and 'status' exist ONLY inside this if/else block.
	if code, status := getStatus(); code == 200 {
		fmt.Printf("Success! Status: %s (%d)\n", status, code)
	} else {
		fmt.Printf("Error Code: %d\n", code)
	}
}

2. The switch Statement (No break Required!)
#

In C, Java, or JavaScript, forgetting a break in a switch statement causes dangerous fallthrough bugs. In Go, branches break automatically.

package main

import (
	"fmt"
	"time"
)

func main() {
	// 1. Standard Expression Switch
	today := time.Now().Weekday()
	switch today {
	case time.Saturday, time.Sunday:
		fmt.Println("Weekend! Time to relax.")
	default:
		fmt.Println("Workday! Back to code.")
	}

	// 2. Tagless Switch (Replaces long if/else chains)
	score := 85
	switch {
	case score >= 90:
		fmt.Println("Grade: A")
	case score >= 80:
		fmt.Println("Grade: B")
	default:
		fmt.Println("Grade: C")
	}
}

3. The 4 Forms of the for Loop
#

Because Go has no while keyword, for fulfills all looping patterns.

PatternEquivalent in Other LanguagesGo Syntax
C-Style Loopfor (int i=0; i<5; i++)for i := 0; i < 5; i++
While Loopwhile (condition)for condition
Infinite Loopwhile (true)for {}
Range Loopforeach (item in list)for i, v := range slice
package main

import "fmt"

func main() {
	// 1. Standard C-style loop
	for i := 1; i <= 3; i++ {
		fmt.Printf("Count: %d\n", i)
	}

	// 2. While-style loop
	n := 1
	for n < 100 {
		n *= 2
	}
	fmt.Printf("Final Power of 2: %d\n", n)

	// 3. Iterating over a slice using range
	fruits := []string{"Apple", "Banana", "Cherry"}
	for index, fruit := range fruits {
		fmt.Printf("Index %d: %s\n", index, fruit)
	}
}

4. Troubleshooting & Common Errors
#

Error 1: syntax error: unexpected newline, expecting {
#

The Cause: Placing the opening curly brace { of an if or for statement on a new line. Go uses automatic semicolon insertion, so { MUST be on the same line.

// 🔴 Invalid
if x > 0
{
}

// 🟢 Valid
if x > 0 {
}

Summary & Next Steps
#

In this episode:

  • We scoped variables inside if initialization statements.
  • We used tagless switch expressions without explicit break statements.
  • We mastered the 4 forms of the for loop in Go.

In Episode 3: Functions, Defer & Closures, we will explore multiple return values, variadic parameters, and defer resource cleanup!

go - This article is part of a series.
Part 2: This Article