xxxxxxxxxx
var slice = []string{"Apple", "Orange", "Kiwi"}
for index, sliceItem := range slice { // You can omit index or sliceItem with a _
fmt.Println("Index in slice:", index)
fmt.Println("Fruit:", sliceItem)
}
xxxxxxxxxx
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
xxxxxxxxxx
// Program that loops over a slice using for loop
package main
import "fmt"
func main() {
numbers := []int{2, 4, 6, 8, 10}
// for loop that iterates through the slice
for i := 0; i < len(numbers); i++ {
fmt.Println(numbers[i])
}
}
xxxxxxxxxx
s := []int{1,2,3}
for i := 0; i < len(s); i++ {
fmt.Println(s[len(i)-1-i])
}