In Go, loops are essential for repeating actions or iterating over data structures like arrays and slices.
Go has a simplified approach to looping compared to many other languages, as it only supports the for loop, which can be used in various ways to achieve different looping behaviors.
In this tutorial, we’ll cover:
1. Basic for Loop
The basic for loop in Go is similar to loops in other languages. It includes an initialization statement, a condition, and a post statement, all separated by semicolons.
package main import "fmt" func main() { for i := 0; i < 5; i++ { fmt.Println("Iteration:", i) } }
Output:
Iteration: 0 Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4
In this example:
- for i := 0; i < 5; i++ initializes i to 0, checks the condition i < 5, and increments i after each iteration.
- The loop runs five times, from i = 0 to i = 4.
2. for Loop with a Condition
The for loop in Go can also work like a while loop by omitting the initialization and post statements. This approach repeats the loop while a condition is true.
package main import "fmt" func main() { count := 1 for count <= 5 { fmt.Println("Count:", count) count++ } }
Output:
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
In this example:
- for count <= 5 checks if count is less than or equal to 5.
- The loop increments count each time, stopping when count becomes greater than 5.
3. Infinite for Loop
An infinite loop in Go can be created by writing a for loop without any conditions. This type of loop will run indefinitely unless you use a break statement to exit it.
package main import "fmt" func main() { count := 0 for { if count == 3 { break // Exit the loop when count reaches 3 } fmt.Println("Infinite loop iteration:", count) count++ } }
Output:
Infinite loop iteration: 0 Infinite loop iteration: 1 Infinite loop iteration: 2
In this example:
- for without conditions creates an infinite loop.
- break exits the loop when count reaches 3.
4. for Loop with range
The for loop with range is used for iterating over elements of arrays, slices, maps, and strings. It provides the index and the value of each element in the collection.
Iterating over a Slice
package main import "fmt" func main() { numbers := []int{10, 20, 30, 40, 50} for index, value := range numbers { fmt.Println("Index:", index, "Value:", value) } }
Output:
Index: 0 Value: 10 Index: 1 Value: 20 Index: 2 Value: 30 Index: 3 Value: 40 Index: 4 Value: 50
In this example:
- for index, value := range numbers iterates over each element of the numbers slice, providing both the index and value.
Iterating over a Map
package main import "fmt" func main() { scores := map[string]int{"Alice": 85, "Bob": 90, "Charlie": 78} for key, value := range scores { fmt.Println("Name:", key, "Score:", value) } }
Output:
Name: Alice Score: 85 Name: Bob Score: 90 Name: Charlie Score: 78
In this example:
- for key, value := range scores iterates over each key-value pair in the scores map.
Iterating over a String
package main import "fmt" func main() { message := "Hello" for index, char := range message { fmt.Printf("Index: %d Character: %c\n", index, char) } }
Output:
Index: 0 Character: H Index: 1 Character: e Index: 2 Character: l Index: 3 Character: l Index: 4 Character: o
In this example:
- for index, char := range message iterates over each character in the string message.
Note: When iterating over a string, char is the Unicode code point of each character.
5. Breaking and Continuing Loops
- break: Exits the loop entirely.
- continue: Skips the current iteration and moves to the next.
package main import "fmt" func main() { for i := 1; i <= 5; i++ { if i == 3 { continue // Skip iteration when i == 3 } if i == 5 { break // Exit the loop when i == 5 } fmt.Println("Value:", i) } }
Output:
Value: 1 Value: 2 Value: 4
In this example:
- continue skips the iteration when i is 3.
- break exits the loop when i is 5.
6. Nested Loops
You can use a loop inside another loop. Nested loops are useful for working with multidimensional data structures like matrices.
package main import "fmt" func main() { matrix := [][]int{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, } for i, row := range matrix { for j, value := range row { fmt.Printf("matrix[%d][%d] = %d\n", i, j, value) } } }
Output:
matrix[0][0] = 1 matrix[0][1] = 2 matrix[0][2] = 3 matrix[1][0] = 4 matrix[1][1] = 5 matrix[1][2] = 6 matrix[2][0] = 7 matrix[2][1] = 8 matrix[2][2] = 9
In this example:
- A nested for loop iterates over a 2D slice (matrix), printing each element’s indices and value.
7. Best Practices for Loops in Go
a) Use for with range for Simple Iteration
When iterating over collections like slices, maps, or strings, use for with range for a cleaner and more idiomatic approach.
for _, value := range slice { fmt.Println(value) }
b) Avoid Infinite Loops When Possible
Use infinite loops only when necessary (e.g., in servers or background processes), and ensure there’s a clear way to exit them to avoid endless executions.
for { if condition { break // Use break to exit the loop } }
c) Use continue and break Sparingly
Frequent use of continue and break can make loops harder to understand. Structure your loops to minimize their use when possible.
d) Be Careful with Nested Loops
Nested loops can become complex and impact performance. Avoid deeply nested loops when possible or consider alternative designs.
for i := 0; i < len(matrix); i++ { for j := 0; j < len(matrix[i]); j++ { // Perform operations } }
Summary
In this tutorial, we covered the basics of loops in Go:
- Basic for Loop: Using for with initialization, condition, and post statements.
- for Loop with a Condition: A simpler for loop that works like a while loop.
- Infinite for Loop: Running a loop indefinitely, with break to exit.
- for Loop with range: Iterating over collections like slices, maps, and strings.
- Breaking and Continuing Loops: Using break to exit and continue to skip iterations.
- Nested Loops: Using loops within loops for multidimensional structures.
- Best Practices for Loops in Go: Writing clean and efficient loops.
Understanding loops in Go will allow you to efficiently work with collections, repeat operations, and manage control flow in your programs. Go’s simple for loop syntax makes it easy to learn while still providing powerful capabilities for different types of looping.