golang range loop code example
Example 1: golang loop through array
arr := []int{1, 2, 3, 4, 5}
//using range
for index, ele := range arr { // you can escape index by _ keyword
fmt.Println(index, ele)
}
Example 2: go iterate over slice
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
Example 3: range in go
kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}