OneBite.Dev - Coding blog in a bite size

iterate over an array in Go

Code snippet on how to iterate over an array in Go

  package main

  import "fmt"

  func main() {
    arr := [3]int{10, 20, 30}

    for i, v := range arr {
        fmt.Printf("arr[%d] is %d\n", i, v)
    }
  }

This code iterates over an array in Go programming language. The array, arr, contains three elements: 10, 20, and 30. The for loop starts, setting a variable i to the index number and setting v to the value of the element in the array at position i. The fmt.Printf function prints the element, showing the index position and the value of the element. The for loop continues until the end of the array is reached. Lastly, the program prints a line indicating the index position and value of each element in the array.

go