Go Mastery: A Comprehensive Guide - Part 2: Control Flow (If, Switch, Loops)
Go Mastery: A Comprehensive Guide - Part 2: Control Flow (If, Switch, Loops)
Introduction
Control flow is how we dictate the execution path of our Go programs. Go keeps it simple, focusing on readability and maintainability.
If/Else Statements
In Go, there are no parentheses around conditions, but curly braces are mandatory.
1
2
3
4
5
if x > 10 {
fmt.Println("x is greater than 10")
} else {
fmt.Println("x is 10 or less")
}
Switch Statement
The switch statement in Go is powerful and flexible. It breaks automatically, so you don’t need break at the end of each case.
1
2
3
4
5
6
7
8
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
fmt.Printf("%s.\n", os)
}
For Loop
In Go, there is only one looping construct: for.
Standard Loop
1
2
3
for i := 0; i < 5; i++ {
fmt.Println(i)
}
While Loop (equivalent)
1
2
3
for n < 10 {
n++
}
Infinite Loop
1
2
3
for {
// Infinite loop
}
Conclusion
We have mastered the core control flow constructs of Go. These simple tools allow you to build complex logic with clarity. In the next part, we will look into data structures like arrays, slices, and maps.
Suggested Reading
This post is licensed under
CC BY 4.0
by the author.