Introduction to for Loops in Go Programming
Introduction to for Loops
Are you ready to level up your Go programming skills? We are moving into more advanced techniques to take full control of Go's capabilities. This lesson focuses on the for loop — a versatile and powerful tool in Go that will enhance your coding efficiency tremendously.
Exploring for Loops
In Go, a for loop allows us to execute a block of code a certain number of times or over a collection. It's incredibly useful for handling repetitive tasks without manually programming each repetition.
Classic "for" Loop Syntax
The traditional syntax for a for loop in Go consists of three components: initialization, condition, and increment. This is typically used when you know in advance how many times you'd like the loop to run. Here's an example:
In this example:
- Initialization:
i := 0sets up a loop variableistarting at0. - Condition:
i < 5continues the loop as long asiis less than5. - Increment:
i++increasesiby1after each iteration.
Running this loop, you'd see:
This structure provides a clear and controlled way to run code a specified number of times.
Using for Loops with Collections
For loops become even more powerful when combined with Go's capability to iterate over collections. For example, consider visiting each country in a list for a trip. Let's see what it looks like in Go:
In this scenario, the loop iterates over tripCountries, with range used to specify the collection to iterate over. The loop assigns each element to the variable country during each iteration and executes the block of code with fmt.Println.
Running the loop, you would see:
