Here we are going to explain, usage of range on slices in for loop
usage of range on []int slice for loop
// declare and init values in slice
nums := []int{2, 3, 4}
//iterate nums slice with range
//i will have index and num will have value in index
for i, num := range nums {
fmt.Printf("i=%d num=%d\n", i, num)
}
output:
i=0 num=2
i=1 num=3
i=2 num=4
usage of range on map[string]string slice for loop
//define map with data with key/value pairs
map1 := map[string]string{"A": "Apple", "B": "Banana"}
//iterates over key/value pairs
for k, v := range map1 {
fmt.Printf("%s -> %s\n", k, v)
}
//just on key
for k := range map1 {
fmt.Printf("key: %s value: %s\n", k, map1[k])
}
output:
A -> Apple
B -> Banana
key: A value: Apple
key: B value: Banana
how to use range in golang
posted on 2022-05-03 08:28:11 - Go lang Tutorials
find variable type in golang
posted on 2022-05-03 05:24:55 - Go lang Tutorials