loop through array golang code example
Example 1: golang loop through array
arr := []int{1, 2, 3, 4, 5}
for index, ele := range arr {
fmt.Println(index, ele)
}
Example 2: loop list golang
a := []string{"Foo", "Bar"}
for i, s := range a {
fmt.Println(i, s)
}
Example 3: golang iterate through slice
var slice = []string{"Apple", "Orange", "Kiwi"}
for index, sliceItem := range slice {
fmt.Println("Index in slice:", index)
fmt.Println("Fruit:", sliceItem)
}
Example 4: go iterate over slice
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)