Control Flow
Control flow constructs are a key building block of any computer program as they allow you to express complex behaviors with conditions and iteration. Go's support for control flow reflects its minimalistic design, which is why you'd mostly see a couple of variations of conditional statements and one version of loop in the entire language specification. It may seem surprising, but this makes Go easier to read, as it forces the same design patterns on all programs. Let's start with the simplest and the most common control flow blocks.
For Loops
In its simplest form, the for loop allows you to iterate over a range of integers while doing some work in each iteration. For example, this is how you would print all numbers from 0 to 4:
func main() {
for i := 0; i < 5; i++ {
fmt.Println(i)
}
}
The first line has the init statement i := 0
, the condition statement i < 5
and the post statement i++
separated by semicolons (;
). The code continues...