Rabi Siddique
203 words
1 minutes
Loops in Golang
2023-01-05

Go provides two types of loops: the for loop and the for-range loop.

The for Loop#

The for loop in Go is similar to for loops in other languages. It consists of three parts: the initialization, the condition, and the post statement. The initialization is executed before the loop starts, the condition is checked before each iteration, and the post statement is executed at the end of each iteration.


package main

import "fmt"

func loops() {
    // Print the numbers from 1 to 10 using a for loop
    for i := 1; i <= 10; i++ {
        fmt.Println(i)
    }
}

The for-range Loop#

The for-range loop is used to iterate over the elements of an array, slice, string, or map. It provides a convenient syntax for working with collections.

for key, value := range collection {
    // body of the loop
}

  • key: The index or key of the current element.
  • value: The value of the current element.

Here is an example:

package main

import "fmt"

func loops() {
    // Declare an array of integers
    a := [5]int{1, 2, 3, 4, 5}

    // Iterate over the elements of the array using for-range
    for i, v := range a {
        fmt.Println("Index:", i, "Value:", v)
    }
}

func main() {
    loops()
}

Loops in Golang
https://rabisiddique.com/posts/loops-in-golang/
Author
Rabi Siddique
Published at
2023-01-05