You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Go provides a small, powerful set of control flow statements: if/else, switch, for, and defer. Unlike many languages, Go has only one loop construct — the for loop — which covers all looping patterns.
if x > 10 {
fmt.Println("x is greater than 10")
}
Note: no parentheses around the condition, but braces are required.
if x > 10 {
fmt.Println("big")
} else if x > 5 {
fmt.Println("medium")
} else {
fmt.Println("small")
}
Go allows a short statement before the condition — perfect for error handling:
if err := doSomething(); err != nil {
fmt.Println("Error:", err)
return
}
// err is not accessible here — scoped to the if block
This pattern is extremely common in Go. The variable declared in the init statement is scoped to the if/else block.
Go's switch is more powerful than in many other languages:
switch day {
case "Monday":
fmt.Println("Start of the week")
case "Friday":
fmt.Println("Almost weekend")
case "Saturday", "Sunday":
fmt.Println("Weekend!")
default:
fmt.Println("Midweek")
}
| Feature | Go | C / Java |
|---|---|---|
| Automatic break | Yes — each case breaks automatically | No — must add break explicitly |
| Fallthrough | Explicit with fallthrough keyword | Default behaviour |
| Multiple values | case "a", "b": | Requires fallthrough |
| Expressions | Cases can be expressions, not just constants | Constants only (Java: limited) |
A switch with no condition is equivalent to if/else if/else:
switch {
case score >= 90:
grade = "A"
case score >= 80:
grade = "B"
case score >= 70:
grade = "C"
default:
grade = "F"
}
Like if, switch supports an init statement:
switch os := runtime.GOOS; os {
case "linux":
fmt.Println("Linux")
case "darwin":
fmt.Println("macOS")
default:
fmt.Println(os)
}
A type switch tests the type of an interface value:
switch v := value.(type) {
case int:
fmt.Println("Integer:", v)
case string:
fmt.Println("String:", v)
case bool:
fmt.Println("Boolean:", v)
default:
fmt.Printf("Unknown type: %T\n", v)
}
Go has only one loop construct: for. It replaces while, do-while, and for loops from other languages.
for i := 0; i < 10; i++ {
fmt.Println(i)
}
for x < 100 {
x *= 2
}
for {
// runs forever (use break or return to exit)
if done {
break
}
}
range iterates over slices, arrays, maps, strings, and channels:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.