Loops in Go: For and Range
In Go, control structures are used to change the execution flow of a program. Among these structures, loops have a significant place in Go programming. In this article, we will focus on the key looping structures in Go, namely For
and Range
.
For Loop
In Go, we only have one looping construct, which is the for
loop. The for
loop in Go can be used in three different ways.
Basic For Loop
The basic for
loop is similar to for
loops in other programming languages like C, Java, etc. It includes initialization, condition, and increment/decrement.
Here is the basic syntax for the for
loop:
for initialization; condition; increment/decrement {
// Code to be executed
}
Let's look at an example:
for i := 0; i < 5; i++ {
fmt.Println(i)
}
In the above example, the loop will run five times, and it will print the numbers from 0 to 4.
Conditional For Loop
The for
loop can also be used as a while loop, where it runs until a certain condition is met.
Here is the syntax:
for condition {
// Code to be executed
}
And here is an example:
i := 0
for i < 5 {
fmt.Println(i)
i++
}
In this example, the loop will run until i
is less than 5.
Infinite For Loop
The for
loop can also be used to create an infinite loop. An infinite loop continues indefinitely and only stops with external intervention or when a break statement is found.
Here's how you can create an infinite loop:
for {
// Code to be executed
}
Range
The range
keyword in Go is used in for loop to iterate over items of an array, slice, channel, or map.
Here is the basic syntax of range
in a for
loop:
for key, value := range collection {
// Code to be executed
}
Let's take a look at an example:
names := []string{"John", "Doe", "Jane"}
for i, name := range names {
fmt.Printf("At index %d, name is %s\n", i, name)
}
In this example, the range
keyword is used to iterate over the names
slice. On each iteration, it returns two values. The first is the index, and the second is a copy of the element at that index.
Conclusion
The for
loop and range
keyword are powerful features of the Go programming language for controlling the flow of your program. Whether you're iterating through basic loops or iterating over data structures with range
, you have the tools to handle repetition with ease. As you continue learning Go, you'll find even more ways to use these constructs to write efficient and effective code.