How can you iterate over the elements of an array or slice in Go?

0149

In Go, you can iterate over the elements of an array or slice using a for loop. Here are two common methods:

1. Using a traditional for loop:

package main

import "fmt"

func main() {
    arr := []int{1, 2, 3, 4, 5}
    
    for i := 0; i < len(arr); i++ {
        fmt.Println(arr[i])
    }
}

2. Using the range keyword:

package main

import "fmt"

func main() {
    arr := []int{1, 2, 3, 4, 5}
    
    for index, value := range arr {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

Explanation:

  • Traditional for loop: You manually control the index and access each element using the index.
  • range keyword: This provides both the index and the value of each element in the slice, making it more concise and easier to read.

Feel free to ask if you need further clarification or examples!

0 Comments

no data
Be the first to share your comment!