Go Language for Loop Examples

Go provides several ways to perform looping, including the for loop. Here are some examples of using the for loop in Go:

  1. Classic for loop:
for i := 0; i < 10; i++ {
fmt.Println(i)
}

This loop will start from 0, continue until i is less than 10, and increment i by 1 on each iteration.

  1. for loop with range:
numbers := []int{1, 2, 3, 4, 5}
for index, value := range numbers {
fmt.Println("Index:", index, "Value:", value)
}

In this example, range is used to iterate over an array of integers. index and value are used to capture the index and value of each element in the array on each iteration.

  1. for loop with break:
for i := 0; i < 10; i++ {
if i == 5 {
break
}
fmt.Println(i)
}

In this example, the break statement is used to break out of the loop when i is equal to 5.

  1. for loop with continue:
for i := 0; i < 10; i++ {
if i%2 == 0 {
continue
}
fmt.Println(i)
}

In this example, the continue statement is used to skip an iteration when i is even. The loop will only print odd numbers.

These are some basic examples of using the for loop in Go. You can use the for loop to perform different types of operations based on your requirements.

Leave a Comment