Loops are an essential part of any programming language. It does a single task multiple times. In this post, we will be diving deeper with the for loops in Go.
The for-loop syntax
The for loop is one of the most common loops in programming. Almost every language has it. The for loop in Go works just like other languages. The loop starts with the keyword for. Then it initializes the looping variable then checks for condition, and then does the postcondition. Below is the syntax of for-loop in Golang.
for initialization; condition; postcondition {
// do something
}
Declaring a for-loop
Now, we will see how to declare and use for loop. It is pretty simple after you know how the syntax actually looks like. Here is an example showing the for-loop in action.
package main
import (
"fmt"
)
func main() {
for i:=0; i<3; i++ { // start of the execution block
fmt.Println("Hello") // prints "Hello" 3 times
} // end
}
In the code above, the variable i is initialized and then matched with the condition. After that, there is a postcondition which is to increment by 1. Now, the postcondition can be anything. The incrementation is a stepping mechanism which takes the loop forward.
The infinite for-loop
We can create an infinite for-loop. Which will be running continuously. Simply removing the conditional clauses will make the loop an infinite one. Here is shown the infinite for-construct.
for {
// this block executes infinitely
}
To stop the infinite execution after certain condition matches, Go has a keyword called break, which can be used to break out of the loop.
The conditional for-loop in Golang
Simply excluding the initialization and postcondition, we can create another kind of for-loop which is the conditional for-loop. It only checks the condition and runs if it matches. An example would be as follows.
package main
import (
"fmt"
)
func main() {
i := 0
for i<5 {
fmt.Println(i) // prints 0 2 4
i += 2
}
}
The range-for loop
Sometimes we need to iterate over a slice or array of items. In that case, using the range function along with for is the way to go. It makes the code much simpler. Here is the range-for loop in action.
package main
import (
"fmt"
)
func main() {
var items []int = []int{1, 2, 3, 4, 5}
for i, v := range items {
fmt.Println(i, v)
}
// output
// 0 1
// 1 2
// 2 3
// 3 4
// 4 5
}
The range-for gives two things to work with, one is the current index and the other is the current value. If the current value is the only thing needed then we can ignore the index using the blank identifier.
package main
import (
"fmt"
)
func main() {
var items []int = []int{1, 2, 3, 4, 5}
for _, v := range items {
fmt.Println(v)
}
}
The range-for with maps
Range-for can be used with maps as well. Which will provide us the key and value both at the same time. With the key being the index. It is a great for-construct which can substantially reduce code and make the code more concise. Here is an example showing how to use range-for with maps.
package main
import (
"fmt"
)
func main() {
var m map[int]string = map[int]string{
1: "One",
2: "Two",
3: "Three",
}
for k, v := range m {
fmt.Println(k, v)
}
// output
// 1 One
// 2 Two
// 3 Three
}
The nested-for loop
Loops in Go can be nested arbitrarily. Here are two for-loops nested.
package main
import (
"fmt"
)
func main() {
for i := 0; i<2; i++ {
for j := 0; j<2; j++ {
fmt.Println(i, j)
}
}
// 0 0
// 0 1
// 1 0
// 1 1
}
Using labels with the for-loop
We can use labels to break out of an ongoing loop. All we need to do is to create a label that points to the intended segment of the code. Here is an example.
package main
import (
"fmt"
)
func main() {
outside: // declare the label
for i := 0; i<2; i++ {
for j := 0; j<2; j++ {
if i < j {
break outside // break to that label
}
fmt.Println(i, j)
}
}
// prints 0 0
}
The continue statement in for-loop
Continue is a keyword that lets us skip the segment of the code and forces us to move us to the next iteration. Below is an example showing the usage of the continue statement in Go.
package main
import (
"fmt"
)
func main() {
for i := 0; i<2; i++ {
for j := 0; j<2; j++ {
if i < j {
continue
}
fmt.Println(i, j)
}
}
// 0 0
// 1 0
// 1 1
}