range in golang code example
Example 1: go loop through map
for k, v := range m {
fmt.Printf("key[%s] value[%s]\n", k, v)
}
for k := range m {
fmt.Printf("key[%s] value[%s]\n", k, m[k])
}
Example 2: 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 3: go iterate over slice
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
Example 4: golang range arrat
for i, num := range nums {
if num == 3 {
fmt.Println("index:", i)
}
}
Example 5: range in go
kvs := map[string]string{"a": "apple", "b": "banana"}
for k, v := range kvs {
fmt.Printf("%s -> %s\n", k, v)
}