Go programs do more than evaluate expressions: they make decisions, repeat work, and exit loops deliberately. if, switch, and for control which statements run. Go uses one loop keyword, for, rather than separate while or do-while statements. Its range clause iterates over collections, while break and continue alter loop execution.
This is OSGo.004 in the complete Open CERT programming rotation. It follows OSGo.003: Operators and Expressions, which supplied the comparison and logical expressions used here. If the syntax is unfamiliar, review OSGo.002: Variables and Basic Types or OSGo.001: The Go Toolchain first.
Learning objectives
- Write conditional branches using
if,else if, andelse. - Use an initialization statement scoped to an
if. - Choose between a value
switchand a condition-onlyswitch. - Recognize classic, condition-only, and unbounded
forloops. - Iterate over a slice with
range; distinguish the index from the copied value. - Use
breakto leave a loop andcontinueto skip to its next iteration. - Run a complete working Go program and interpret its output.
1. Conditions: if, else if, and else
A Go if expects an expression of type bool. Unlike C-style syntax, the condition does not need parentheses, but braces are mandatory. Go tests the branches from top to bottom and executes the first matching branch.
temperature := 76
if temperature >= 85 {
fmt.Println("STOP: overheat")
} else if temperature >= 70 {
fmt.Println("CHECK COOLING")
} else {
fmt.Println("NORMAL")
}
The first comparison is false because 76 is below 85. The second is true because 76 is at least 70, so the output is CHECK COOLING. The else branch is skipped. A semicolon can introduce a short setup statement: if value := 76; value >= 70 { ... }. That variable is scoped to the if statement and any attached else branches.
Video: TechWorld with Nana — Golang Tutorial for Beginners (2021). Go conditionals at 1:24:24, switch at 1:54:02, and loops at 1:11:12.
In a real service, such decisions might determine whether a server fan alert is raised, a sensor reading is logged, or a task proceeds. Use clearly defined thresholds and never assume example values are safe production limits.
2. Switching between cases
Use switch when several cases depend on one value. A Go switch does not fall through by default: when a matching case finishes, the switch ends. Go does not require a break after each case.
status := "warning"
switch status {
case "critical":
fmt.Println("stop")
case "warning", "degraded":
fmt.Println("inspect")
default:
fmt.Println("normal")
}
The output is inspect. A case may match several comma-separated values. For checks that are better expressed as conditions, write switch { case temperature >= 85: ... }; this is an expressionless switch whose cases are tested in order. fallthrough is available for specialized cases, but it transfers control to the next clause without retesting that case, so avoid it when ordinary branching is clearer.
Compare the Go specification’s switch rules with the older C# operators and branching background: a similar surface syntax does not imply identical control-flow rules.
3. One loop keyword: for
Go uses for in three common forms. A traditional loop provides initialization, a condition, and an update. A condition-only form is Go’s equivalent of a while loop. An unconditional for { ... } repeats until a branch exits.
// Three-part loop
for i := 0; i < 3; i++ {
fmt.Println(i) // 0, 1, 2
}
// Condition-only loop
count := 0
for count < 3 {
count++
}
// Open-ended loop with a deliberate exit
for {
if count >= 3 {
break
}
count++
}
The three-part loop initializes i once, checks the condition before each iteration, and runs i++ after the body. An open-ended loop without a reachable exit can run indefinitely, so command-line applications and background services should define appropriate termination conditions.
4. Iterating with range, break, and continue
A for ... range loop can yield both an index and an element value for a slice. The value is assigned to an iteration variable, so changing that copy does not update the original slice element. Use for i := range readings when you need to modify readings[i] directly.
readings := []int{40, 75, 92}
for index, value := range readings {
fmt.Println(index, value)
}
// 0 40
// 1 75
// 2 92
Video: TechWorld with Nana — Full Golang Tutorial, Build a TodoList App (2024). Hands-on slice iteration and for loops from 36:36 and 44:20.
continue skips the remainder of the current loop body and starts the next iteration. break exits the innermost enclosing for, switch, or select. In nested loops, a labeled break Outer can explicitly exit a named outer loop. For a string, range produces byte offsets and Unicode code points; for maps, iteration order is unspecified.
5. Mini lab: flag overheated equipment readings
Create a file named main.go containing the complete program below. The thresholds are illustrative. It combines a decision tree, a condition-only switch, and a range loop that ignores low readings and stops at the first critical reading.
package main
import "fmt"
func main() {
temperature := 76
if temperature >= 85 {
fmt.Println("STOP: overheat")
} else if temperature >= 70 {
fmt.Println("CHECK COOLING")
} else {
fmt.Println("NORMAL")
}
switch {
case temperature >= 85:
fmt.Println("status: critical")
case temperature >= 70:
fmt.Println("status: warning")
default:
fmt.Println("status: nominal")
}
readings := []int{40, 75, 92}
for i, value := range readings {
if value < 70 {
continue
}
fmt.Printf("sample %d: %d°C\n", i, value)
if value >= 90 {
fmt.Println("Stop at first critical reading")
break
}
}
}
Run gofmt -w main.go to format the source and go run main.go to execute it. The program was compiled and run for this lesson using Go 1.23.2. Its exact console output was:
CHECK COOLING
status: warning
sample 1: 75°C
sample 2: 92°C
Stop at first critical reading
Why was sample 0 absent? Its value, 40, triggered continue. Why did processing stop after sample 2? Its value, 92, triggered break. This is a filtering pattern frequently used in device diagnostics, data validation, and systems monitoring. For related loop syntax in another language, compare OSC.005: C Loops and OSRust.005: Rust Control Flow.
6. Common mistakes and troubleshooting
- Parentheses and braces: Go omits parentheses in ordinary
ifconditions but requires curly braces. - Unexpected case execution: Go switch cases stop automatically. Do not insert
fallthroughunless the next clause must run even when it does not match. - Missing range variables: use
_to ignore an index or value you do not need. - Map traversal: never depend on a particular map iteration order; collect and sort keys when ordering matters.
- Accidental infinite loops: ensure a condition eventually changes or the loop has an intentional termination path.
- Wrong break target: a plain
breakinside aswitchexits that switch, not necessarily an enclosing loop.
7. Knowledge check
- What is printed for temperature 65 in the first example?
- Does a matching Go switch case run the next case automatically?
- Which loop form replaces a traditional while statement?
- What does
continuedo to the current loop iteration? - Can
rangeover a map guarantee key order? - What changes if the lab replaces
breakwithcontinueat 92°C?
Answer guide: (1) NORMAL; (2) no; (3) for condition { ... }; (4) skips to the next iteration; (5) no; (6) the loop will advance to later readings rather than stop at the first critical value.
Official references and next lesson
The authoritative sources for these constructs are A Tour of Go: For, A Tour of Go: Switch, and the Go Language Specification: For Statements. Note that Go 1.22 changed loop-variable behavior, giving each iteration its own iteration variables; modern examples should not assume older closure-capture semantics. The next Go lesson, OSGo.005, can focus on functions, parameters, and return values. The overall certificate rotation advances to the Java track rather than repeating Go immediately.
Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support our work and help further secure the integrity of our research initiatives, please scan the QR code below to donate 5,000 sats.

For mobile scanning, open the lesson on a larger screen and scan the QR code with a compatible Bitcoin wallet. Verify the destination address before sending: 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb.
BitcoinVersus.tech is not a financial advisor. This media platform reports on financial subjects purely for informational purposes.

Leave a Reply