Loops
Looping in golang is easy! There is only one type of loop
Last updated
Looping in golang is easy! There is only one type of loop
Last updated
The for
loop is the only looping construct in golang. Although golang does not have reserved words like while
for loops where the condition is evaluated in the loop body, the for
loop can be extended to support such patterns. Let's look at some examples below
Golang's for
statement support the classic three-statement for loops, where we have an initial value, a condition that is tested every iteration of the loop, and some action to perform on the loop variant. Here's how that works in golang
// for loop with initializer, condition, and increment
fmt.Println("For loop")
for j := 0; j < 5; j++ {
fmt.Println("The current value is ", j)
}
We can write a while loop using the for
keyword. The thing worth noting here is the loop variable initialization happens outside the loop.
// while loops in go use the for <condition> format
fmt.Println("While loop")
i := 0
for i < 5 {
fmt.Println(i)
i++
}
For loops without an exit condition will result in an infinite loop
// infinite loop example.
// caution: do not run the following code
fmt.Println("Infinite loop")
k := 0
for {
fmt.Println(k)
k++
}
foreach loops are a useful construct in many languages and golang provides support for this through the range
keyword. Range loops are useful when we need to iterate over individual elements of a list, array, or map (or other container types)
// for-each loops (also known as range loops)
fmt.Println("\nRange loop")
nums := []int{1, 2, 3, 4, 5}
for index, num := range nums {
fmt.Println(index, num)
}
We can skip over parts of the loop with the continue
keyword, or break out of loops using break
in the loop body.
// break loop
fmt.Println("Break loop")
for l := 0; l < 5; l++ {
if l == 3 {
// exit the loop when l == 3
break
}
fmt.Println(l)
}
// continue loop
fmt.Println("Continue loop")
for m := 0; m < 5; m++ {
if m == 3 {
// skips over printing 3
continue
}
fmt.Println(m)
}