for
Loop
range
Loop
for
Loop and range
Loop
In Go, looping constructs are essential for iterating over collections and executing repetitive tasks. Two primary looping constructs are the for
loop and the range
loop. While both can be used for iteration, they serve different purposes and have distinct syntax and use cases. This guide will explore the differences between Go's for
loop and range
loop, with practical examples to illustrate their usage.
for
LoopThe for
loop in Go is a versatile construct that can be used in several forms. Its basic syntax involves initialization, condition, and post statement.
Basic Syntax:
Example: Simple **for**
Loop
Explanation:
i := 0
initializes the loop variable i
.i < 5
is the loop condition; the loop runs while i
is less than 5.i++
increments the loop variable after each iteration.The for
loop can also be used to create an infinite loop by omitting the condition.
Example: Infinite **for**
Loop
Explanation:
range
LoopThe range
loop is specifically designed for iterating over slices, arrays, maps, and channels. It simplifies the process of accessing elements and their indices.
Basic Syntax:
Example: **range**
Loop with Slice
Explanation:
index
is the current index of the element in the slice.fruit
is the value at that index.range
with MapsThe range
loop can also iterate over map keys and values.
Example: **range**
Loop with Map
Explanation:
name
is the key in the map.age
is the corresponding value.for
Loop and range
Loop**for**
Loop:
**range**
Loop:
Example: Using **for**
vs. **range**
**for**
Loop:
**range**
Loop:
Example: Ignoring Index with **range**
**for**
Loop:
**range**
Loop:
Example: Infinite **for**
Loop
for
LoopExample: Custom Increment
range
LoopExample: Iterating with **range**
Both for
loops and range
loops in Go serve valuable purposes in iteration but are suited to different scenarios. The for
loop provides flexibility and control, making it ideal for custom iteration needs. The range
loop offers simplicity and convenience for iterating over collections, automatically managing indices and values. Understanding when and how to use each loop type helps you write more efficient and readable Go code.