notes

Go (Golang)

Go Control Flow

Basics of for, range, if, switch, defer

Control Flow

for

Go has only one looping keyword: for. It has three forms.

Classic three-part loop (init; condition; post):

sum := 0
for i := 0; i < 10; i++ {
	sum += i
}

While-style (condition only) - like while in other languages:

for sum < 100 {
	sum += sum
}

Infinite loop - use break to exit:

for {
	if sum2 > 10 {
		break
	}
	sum2 += sum2
}

continue skips to the next iteration.

range

range iterates over a collection, or over a range of integers.

for i := range 10 { // i = 0..9
	fmt.Println(i)
}

Over a slice/array/map it yields the index (and value). Use _ to ignore one.

for i, v := range nums {
	fmt.Println(i, v)
}

if

No parentheses around the condition, but braces are required. Like for, an if can start with a short statement whose variables are scoped to the if/else.

if x < 0 {
	// ...
} else {
	// ...
}
if v := f(); v > 0 { // v is scoped to this if/else
	// ...
}

switch

switch is a cleaner chain of if/else. Each case breaks automatically — there is no fall-through unless you explicitly write fallthrough. A case can list several values, and the switch can have an init statement.

switch os := runtime.GOOS; os {
case "darwin":
	fmt.Println("OS X")
case "linux":
	fmt.Println("Linux")
default:
	fmt.Printf("%s.\n", os)
}

A switch with no expression is switch true, handy for long condition chains.

defer

defer schedules a function call to run when the surrounding function returns. Deferred calls are pushed onto a stack, so they run in LIFO order (last deferred runs first).

defer fmt.Println("This will be printed at the end.")

for i := range 10 {
	defer fmt.Println(i) // prints 9, 8, ... 0 at return
}

Arguments passed to a deferred call are evaluated immediately, even though the call itself runs later.

#programming#gocreated 15 Oct 2026

Local graph