Junior — Middle
How to implement a loop over elements of a slice or array in your programming language?
sobes.tech AI
Answer from AI
In Go, iterating over elements of a slice or array is usually done with a for loop using the range construct. It allows iterating over indices and values of the elements.
Example of iterating over a slice:
package main
import "fmt"
func main() {
numbers := []int{10, 20, 30, 40}
// Iterating with index and value
for i, v := range numbers {
fmt.Printf("Index: %d, Value: %d\n", i, v)
}
// If index is not needed
for _, v := range numbers {
fmt.Println(v)
}
}
This loop is convenient and readable; it works with both arrays and slices.