In Go, the for
loop is the only looping construct provided by the language. It’s versatile and efficient for executing a block of code multiple times, often with a unique value in each iteration. Each cycle through the loop is referred to as an iteration.
Syntax of a for Loop
The for
loop in Go can include up to three statements:
for initialization; condition; increment { // code to execute during each iteration }
- Initialization: This sets up the loop control variable.
- Condition: This evaluates before each iteration. If
TRUE
, the loop continues; ifFALSE
, the loop ends. - Increment: This modifies the loop control variable after each iteration.
Note: These statements don’t need to be included within the loop header but must exist elsewhere in the code.
Example 1: Counting from 0 to 4
package main import ("fmt") func main() { for bikes := 0; bikes < 5; bikes++ { fmt.Println(bikes) } }
Output:
0 1 2 3 4
Explanation:
- Initialization:
bikes := 0
sets the starting value to 0. - Condition:
bikes < 5
ensures the loop runs as long asbikes
is less than 5. - Increment:
bikes++
increases the value ofbikes
by 1 in each iteration.
Example 2: Counting in Tens
package main import ("fmt") func main() { for motorcycles := 0; motorcycles <= 100; motorcycles += 10 { fmt.Println(motorcycles) } }
Output:
0 10 20 30 40 50 60 70 80 90 100
Explanation:
- Initialization:
motorcycles := 0
starts at 0. - Condition:
motorcycles <= 100
keeps the loop running whilemotorcycles
is less than or equal to 100. - Increment:
motorcycles += 10
increases the value by 10 with each cycle.
Continue Statement
The continue
statement skips the remainder of the current loop iteration and proceeds to the next iteration.
Example: Skipping a specific value (e.g., 3):
package main import ("fmt") func main() { for models := 0; models < 5; models++ { if models == 3 { continue } fmt.Println(models) } }
Output:
0 1 2 4
Break Statement
The break
statement halts the loop’s execution entirely.
Example: Terminating the loop when a condition is met:
package main import ("fmt") func main() { for brands := 0; brands < 5; brands++ { if brands == 3 { break } fmt.Println(brands) } }
Output:
0 1 2
Nested Loops
Loops can be nested, meaning one loop is placed inside another. The inner loop runs completely during each iteration of the outer loop.
Example: Combining two lists, such as adjectives and motorcycle brands:
package main import ("fmt") func main() { adjectives := [2]string{"sleek", "powerful"} brands := [3]string{"Ducati", "Yamaha", "Honda"} for i := 0; i < len(adjectives); i++ { for j := 0; j < len(brands); j++ { fmt.Println(adjectives[i], brands[j]) } } }
Output:
sleek Ducati sleek Yamaha sleek Honda powerful Ducati powerful Yamaha powerful Honda
Using the range Keyword
The range
keyword provides a convenient way to iterate over elements in arrays, slices, or maps. It returns both the index and the value.
Syntax:
for index, value := range collection { // code to execute during each iteration }
Example: Iterating through motorcycle brands:
package main import ("fmt") func main() { brands := [3]string{"Suzuki", "Honda", "Ducati"} for idx, val := range brands { fmt.Printf("%v\t%v\n", idx, val) } }
Output:
0 Suzuki 1 Honda 2 Ducati
Additional Tips for range
- To ignore the index:
for _, val := range brands { fmt.Println(val) }
Output:Suzuki Honda Ducati
- To ignore the value:
for idx, _ := range brands { fmt.Println(idx) }
Output:0 1 2