Welcome back! I hope you're prepared for another exciting lesson. Our journey through loops in Go continues. You've already built a strong foundation. Now, we'll enrich that knowledge by exploring how to use a conditional for
loop in Go.
Think of a for
loop with a condition in Go as your reliable companion that continues performing a task as long as the condition remains true. It keeps iterating until the condition fails or a break
statement intervenes. Let's illustrate how this works with a code snippet related to planning a trip based on the budget
for the countries you want to visit:
Go1package main 2 3import ( 4 "fmt" 5) 6 7func main() { 8 // We have a budget for the trip, and each country costs a certain amount 9 travelBudget := 5000 10 countryCosts := map[string]int{"France": 1000, "Italy": 800, "Spain": 900, "Japan": 1200} 11 12 totalCost := 0 13 chosenCountries := []string{} 14 15 // Let's add countries to our trip until our budget runs out using a for loop 16 for totalCost < travelBudget && len(countryCosts) > 0 { 17 // Iterate over map to get a country and its cost 18 tried := 0 19 for country, cost := range countryCosts { 20 if totalCost+cost <= travelBudget { 21 totalCost += cost 22 chosenCountries = append(chosenCountries, country) 23 delete(countryCosts, country) 24 } else { 25 tried++ 26 } 27 } 28 29 if len(countryCosts) == tried { 30 // we don't have any more options that can fit within our budget so we can safely exist the loop 31 break; 32 } 33 } 34 35 fmt.Println("Countries chosen for the trip:", chosenCountries) 36}
This code features a for
loop that checks two conditions — whether our totalCost
is less than our travelBudget
, and whether there are still countries left in the countryCosts
map. The loop continues iterating, removing countries from the map, and adding them to our trip until one of the conditions fails.
We are also monitoring how many countries we have checked within our loop. If it so happens that the count of countries checked matches the length of the collection of contries, we have exhausted our options and can exit our loop.
In this case, our budget
permits travel to all the countries, so the loop stops when countryCosts
is empty and there are no more countries to consider. If you adjust the travelBudget
to a lower number, the loop will halt sooner when the first condition is no longer met.
Understanding for loops with conditions extends your ability to automate repetitive tasks and manage iterations flexibly. This knowledge enhances coding efficiency and simplicity. Once mastered, loops provide remarkable versatility, allowing you to tackle complex tasks smoothly.
Isn't that exciting? We're now prepared to start the practice section. You can roll up your sleeves and dive into the world of conditional for loops, refining your Go programming skills one iteration at a time!